<?php

/**
 * Model Remote Data from Vtiger
 * 
 * @category   CRM4Ecommerce
 * @package    CRM4Ecommerce_VtigerSynchronization
 * @author     Philip Nguyen <philip@crm4ecommerce.com>
 * @link       http://crm4ecommerce.com
 */
class CRM4Ecommerce_VtigerSynchronization_Model_Remote extends CRM4Ecommerce_VtigerSynchronization_Model_Abstract {

    public function remote($type, $vtigerId, $to, $storeId = null) {
        $vtigerIds = null;
        if (is_null($storeId)) {
            $storeId = $to;
        } else {
            $from = $vtigerId;
            $vtigerIds = $this->getRecords($type, $from, $to);
            if (is_string($vtigerIds) && str_replace('error-', '', $vtigerIds) != $vtigerIds) {
                print '<br/>';
                print str_replace('error-', '', $vtigerIds);
                return;
            }
        }

        if (!is_null($vtigerIds)) {
            $lastId = $vtigerId;
            $_response = '';
            foreach ($vtigerIds as $vtigerId) {
                $lastId = $vtigerId;
                $response = $this->doRemote($type, $vtigerId, $storeId, true);
                if (str_replace('error-', '', $response) != $response) {
                    $_response .= str_replace('error-', '', $response);
                    print $lastId . '::' . $_response;
                    return;
                } else {
                    $_response .= $response;
                }
            }
            print (intval($lastId) + 1) . '::' . '<br/>' . $_response;
        } else {
            print '<br/>';
            $response = $this->doRemote($type, $vtigerId, $storeId);
            print str_replace('error-', '', $response);
        }
    }

    public function doRemote($type, $vtigerId, $storeId, $showId = false, $data = null) {
        $this->_vtiger_model = $type;
        $this->_function = 'export';
        switch ($type) {
            case 'Leads':
                return $this->remoteLeads($vtigerId, $storeId, $showId, $data);
                break;
            case 'Accounts':
                return $this->remoteAccounts($vtigerId, $storeId, $showId, $data);
                break;
            case 'Contacts':
                return $this->remoteContacts($vtigerId, $showId, $data);
                break;
            case 'Products':
                return $this->remoteProducts($vtigerId, $showId, $data);
                break;
            case 'ProductImages':
                return $this->remoteProductImages($vtigerId, $data);
                break;
            case 'Services':
                return $this->remoteServices($vtigerId, $showId, $data);
                break;
            case 'Quotes':
                return $this->remoteQuotes($vtigerId, $storeId, $showId, $data);
                break;
            case 'SalesOrder':
                return $this->remoteOrders($vtigerId, $showId, $data);
                break;
            case 'Invoice':
                return $this->remoteInvoices($vtigerId, $showId, $data);
                break;
            case 'Activities':
                return $this->remoteActivities($data);
                break;
        }
    }

    public function getRecords($type, $from, $to) {
        $this->_vtiger_model = $type;
        $this->_function = 'exports';
        $postData = array(
            'fromId' => $from,
            'toId' => $to
        );
        $result = $this->post($postData);
        if ($result == '') {
            return 'error-' . Mage::helper('vtigersynchronization')->__("Response from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Records undetermined") . '.<br/>';
        } else {
            return explode(',', $result);
        }
    }

    private function getCustomerGroupCode($group_code) {
        $group = Mage::getModel('customer/group')->getCollection()
                ->addFieldToFilter('customer_group_code', array('eq' => $group_code))
                ->getFirstItem();

        if (is_null($group->getId())) {
            $taxclass = Mage::getModel('tax/class')->getCollection()
                    ->addFieldToFilter('class_type', array('eq' => 'CUSTOMER'))
                    ->getFirstItem();
            $group = Mage::getModel('customer/group')->setCustomerGroupCode($group_code)
                    ->setTaxClassId($taxclass->getId())
                    ->save();
        }
        return $group->getId();
    }

    public function remoteLeads($vtigerId, $storeId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $lead = $data['crm4ecommerce'];
        $customer_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_LEAD, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::CUSTOMER_INFORMATION);
        $customerData = array();
        foreach ($customer_info_mapping as $field) {
            $customerData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_address_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_LEAD, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::CUSTOMER_BILLING);
        $customerBillingData = array();
        foreach ($customer_address_mapping as $field) {
            $customerBillingData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_data = array();
        $customer_billing_data = array();
        $company = '';
        $country_id = '';
        $regions = null;
        $subscribed = null;
        $customer_id = 0;

        $website_name = '';
        $store_group_name = '';
        $store_name = '';
        $has_website_store_change = false;

        foreach ($lead as $key => $value) {
            $value = ($value == '' || (string) $value == '0') ? null : $value;
            if ($key == 'remote_id') {
                $customer_id = $value;
                continue;
            }
            if (key_exists($key, $customerData) && $customerData[$key] != '') {
                if ($customerData[$key] == 'vtiger_logintime' || $customerData[$key] == 'vtiger_logouttime') {
                    continue;
                }
                $customer_data[$customerData[$key]] = $value;
                switch ($customerData[$key]) {
                    case 'prefix':
                        if (!key_exists($key, $customer_billing_data) || $customer_billing_data[$key] == '') {
                            $customer_billing_data['prefix'] = $value;
                        }
                        break;
                    case 'firstname':
                        if (!key_exists($key, $customer_billing_data) || $customer_billing_data[$key] == '') {
                            $customer_billing_data['firstname'] = $value;
                        }
                        break;
                    case 'middlename':
                        if (!key_exists($key, $customer_billing_data) || $customer_billing_data[$key] == '') {
                            $customer_billing_data['middlename'] = $value;
                        }
                        break;
                    case 'lastname':
                        if (!key_exists($key, $customer_billing_data) || $customer_billing_data[$key] == '') {
                            $customer_billing_data['lastname'] = $value;
                        }
                        break;
                    case 'suffix':
                        if (!key_exists($key, $customer_billing_data) || $customer_billing_data[$key] == '') {
                            $customer_billing_data['suffix'] = $value;
                        }
                        break;
                    case 'subscribed_newsleter':
                        if ($value == '1') {
                            $subscribed = true;
                        } else {
                            $subscribed = false;
                        }
                        break;
                    case 'group_id':
                        $customer_data['group_id'] = $this->getCustomerGroupCode($value);
                        break;
                    case 'confirmation':
                        $customer_data['confirmation'] = ($value == '1') ? '0' : '1';
                        break;
                    case 'website_id':
                        $has_website_store_change = true;
                        $website_name = $value;
                        break;
                    case 'store_group_id':
                        $has_website_store_change = true;
                        $store_group_name = $value;
                        break;
                    case 'store_id':
                        $has_website_store_change = true;
                        $store_name = $value;
                        break;
                    case 'gender':
                        $customer_data['gender'] = $this->getCustomerGenderName($value);
                        break;
                }
            } else if (key_exists($key, $customerBillingData) && $customerBillingData[$key] != '') {
                switch ($customerBillingData[$key]) {
                    case 'country_id':
                        $country_id = $this->searchCountry($value);
                        $customer_billing_data['country_id'] = $country_id;
                        if (!is_null($regions)) {
                            if (is_array($regions)) {
                                $customer_billing_data['region_id'] = $regions[$country_id];
                            } else {
                                $customer_billing_data['region_id'] = $regions;
                            }
                        }
                        break;
                    case 'region':
                        $customer_billing_data['region'] = $value;
                        if ($country_id != '') {
                            $region = $this->searchRegionId($value, $country_id);
                            if ($region != $value) {
                                $customer_billing_data['region_id'] = $region;
                            }
                        } else {
                            $regions = $this->searchRegionId($value);
                        }
                        break;
                    default:
                        $customer_billing_data[$customerBillingData[$key]] = $value;
                }
            }
            if ($key == 'company') {
                $company = $value;
            }
        }

        if (!isset($customer_data['email']) || $customer_data['email'] == '') {
            $customer_data['email'] = str_replace('{{vtiger_id}}', $vtigerId, Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/lead_default_email'));
        }
        $customer_data['vtiger_id'] = $vtigerId;
        $customer_data['vtiger_type'] = 'Leads';
        $customer = Mage::getModel('customer/customer')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$customer->getId() && (int) $customer_id > 0) {
            $customer = Mage::getModel('customer/customer')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $customer_id))
                    ->getFirstItem();
        }
        if (!$customer->getId() && isset($customer_data['email']) && $customer_data['email'] != '') {
            $customer = Mage::getModel('customer/customer')->getCollection()
                    ->addFieldToFilter('email', array('eq' => $customer_data['email']))
                    ->getFirstItem();
        }

        if ($customer->getId() > 0) {
            if ($has_website_store_change) {
                $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name);
                if ($storeId) {
                    $storeIds = explode(',', $storeId);
                    $customer_data['website_id'] = $storeIds[0];
                    $customer_data['store_id'] = $storeIds[2];
                    $customer_data['created_in'] = Mage::getModel('core/store')->load($storeIds[2])->getName();
                }
            }

            $customer = Mage::getModel('customer/customer')->load($customer->getId());
            $listAdresses = $customer->getAddresses();

            $primary_address = null;
            foreach ($listAdresses as $address) {
                if (is_null($primary_address)) {
                    $primary_address = $address;
                }
                if ($customer->getDefaultBilling() == $address->getId()) {
                    $primary_address = $address;
                    break;
                }
            }
            $company_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/lead_company_format');
            if ($company_format == '') {
                $company_format = '{{company}} (#{{customer_id}})';
            }
            $company_format = str_replace('{{customer_id}}', $customer->getId(), $company_format);
            $company_format = explode('{{company}}', $company_format);
            $company = str_replace('!@#$%^' . $company_format[0], '', '!@#$%^' . $company);
            $company = str_replace($company_format[1] . '!@#$%^', '', $company . '!@#$%^');
            $company = trim($company, '!@#$%^');
            if (str_replace($customer->getFirstname() . ' ' . $customer->getLastname(), '', $company) == $company) {
                $customer_billing_data['company'] = $company;
            } else {
                $customer_billing_data['company'] = '';
            }
            Mage::getModel('core/session')->setData('remote', true);
            if (!is_null($primary_address)) {
                $primary_address->addData($customer_billing_data)->save();
            } else {
                $primary_address = Mage::getModel('customer/address')->setData($customer_billing_data)
                                ->setCustomerId($customer->getId())->save();
                $customer->setDefaultBilling($primary_address->getId());
                $customer->setDefaultShipping($primary_address->getId());
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($customer->getId())
                    ->setToId($customer->getId())
                    ->setNumberSuccess(1)->setSuccessIds($customer->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($customer->getId(), $customer->getFirstname() . ' ' . $customer->getLastname() . ' (' . $customer->getEmail() . ')')->save();

            if (!is_null($subscribed)) {
                $customer->setIsSubscribed($subscribed);
                if ($subscribed) {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED)->save();
                } else {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED)->save();
                }
            }
            $customer->addData($customer_data);
            $customer->save();

            $wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer->getId(), true);
            $wishListItemCollection = $wishList->getItemCollection();

            foreach ($lead['ref_products'] as $_item => $productid) {
                $flag = false;
                if (count($wishListItemCollection) > 0) {
                    foreach ($wishListItemCollection as $item) {
                        if ($productid == $item->getProduct()->getId()) {
                            $flag = true;
                            break;
                        }
                    }
                }
                if (!$flag) {
                    $wishList->addNewItem(Mage::getModel('catalog/product')->load($productid));
                }
            }
            if (count($wishListItemCollection) > 0) {
                foreach ($wishListItemCollection as $item) {
                    $flag = false;
                    $_id = $item->getProduct()->getId();
                    foreach ($lead['ref_products'] as $_item => $productid) {
                        if ($productid == $_id) {
                            $flag = true;
                            break;
                        }
                    }
                    if (!$flag) {
                        $item = Mage::getModel('wishlist/item')->load($item->getId());
                        $item->delete();
                    }
                }
            }
            $wishList->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer %s (%s) have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                ), $customer->getEmail()
                        ) . '<br/>';
            } else {
                return $customer->getId();
            }
        } else {
            $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name, $storeId);
            $storeIds = explode(',', $storeId);
            $customer_data['website_id'] = $storeIds[0];
            $customer_data['store_id'] = $storeIds[2];
            $customer_data['created_in'] = Mage::getModel('core/store')->load($storeIds[2])->getName();

            $customer = Mage::getModel('customer/customer')
                    ->addData($customer_data);
            Mage::getModel('core/session')->setData('remote', true);
            $customer->save();

            $company_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/lead_company_format');
            if ($company_format == '') {
                $company_format = '{{company}} (#{{customer_id}})';
            }
            $company_format = str_replace('{{customer_id}}', $customer->getId(), $company_format);
            $company_format = explode('{{company}}', $company_format);
            $company = str_replace('!@#$%^' . $company_format[0], '', '!@#$%^' . $company);
            $company = str_replace($company_format[1] . '!@#$%^', '', $company . '!@#$%^');
            $company = trim($company, '!@#$%^');
            if (str_replace($customer->getFirstname() . ' ' . $customer->getLastname(), '', $company) == $company) {
                $customer_billing_data['company'] = $company;
            } else {
                $customer_billing_data['company'] = '';
            }

            $primary_address = Mage::getModel('customer/address')->setData($customer_billing_data)
                            ->setCustomerId($customer->getId())->save();
            $customer = Mage::getModel('customer/customer')->load($customer->getId());
            $customer->setDefaultBilling($primary_address->getId())
                    ->setDefaultShipping($primary_address->getId());
            if (!key_exists('group_id', $customer_data) || $customer_data['group_id'] == '') {
                $customer->setGroupId(Mage::getStoreConfig('customer/create_account/default_group'));
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($customer->getId())
                    ->setToId($customer->getId())
                    ->setNumberSuccess(1)->setSuccessIds($customer->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($customer->getId(), $customer->getFirstname() . ' ' . $customer->getLastname() . ' (' . $customer->getEmail() . ')')->save();

            if (!is_null($subscribed)) {
                $customer->setIsSubscribed($subscribed);
                if ($subscribed) {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED)->save();
                } else {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED)->save();
                }
            }

            $customer->save();
            $customer->sendPasswordReminderEmail();

            $wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer->getId(), true);
            $wishListItemCollection = $wishList->getItemCollection();

            foreach ($lead['ref_products'] as $_item => $productid) {
                $flag = false;
                if (count($wishListItemCollection) > 0) {
                    foreach ($wishListItemCollection as $item) {
                        if ($productid == $item->getProduct()->getId()) {
                            $flag = true;
                            break;
                        }
                    }
                }
                if (!$flag) {
                    $wishList->addNewItem(Mage::getModel('catalog/product')->load($productid));
                }
            }
            if (count($wishListItemCollection) > 0) {
                foreach ($wishListItemCollection as $item) {
                    $flag = false;
                    $_id = $item->getProduct()->getId();
                    foreach ($lead['ref_products'] as $_item => $productid) {
                        if ($productid == $_id) {
                            $flag = true;
                            break;
                        }
                    }
                    if (!$flag) {
                        $item = Mage::getModel('wishlist/item')->load($item->getId());
                        $item->delete();
                    }
                }
            }
            $wishList->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer %s (%s) have been created new successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                ), $customer->getEmail()
                        ) . '<br/>';
            } else {
                return $customer->getId();
            }
        }
    }

    public function remoteAccounts($vtigerId, $storeId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $account = $data['crm4ecommerce'];

        if ($account['is_guest'] == '1' && !Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/account_import_guest')) {
            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__("Error: Synchronization module doesn't allow importing guest account.") . '<br/>';
            } else {
                return null;
            }
        }

        $customer_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_ACCOUNT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::CUSTOMER_INFORMATION);
        foreach ($customer_info_mapping as $field) {
            $customerKeys[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_billing_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_ACCOUNT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::CUSTOMER_BILLING);
        $customerBillingKeys = array();
        foreach ($customer_billing_mapping as $field) {
            $customerBillingKeys[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_shipping_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_ACCOUNT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::CUSTOMER_SHIPPING);
        $customerShippingKeys = array();
        foreach ($customer_shipping_mapping as $field) {
            $customerShippingKeys[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_data = array();
        $customer_billing_data = array();
        $customer_shipping_data = array();
        $company = '';
        $subscribed = null;
        $customer_id = 0;

        $website_name = '';
        $store_group_name = '';
        $store_name = '';
        $has_website_store_change = false;

        foreach ($account as $key => $value) {
            $value = ($value == '' || (string) $value == '0') ? null : $value;
            if ($key == 'remote_id') {
                $customer_id = $value;
                continue;
            }
            if (key_exists($key, $customerKeys) && $customerKeys[$key] != '') {
                if ($customerKeys[$key] == 'vtiger_logintime' || $customerKeys[$key] == 'vtiger_logouttime') {
                    continue;
                }
                switch ($customerKeys[$key]) {
                    case 'confirmation':
                        $customer_data['confirmation'] = ($value == '1') ? '0' : '1';
                        break;
                    case 'group_id':
                        $customer_data['group_id'] = $this->getCustomerGroupCode($value);
                        break;
                    case 'subscribed_newsleter':
                        if ($value == '1') {
                            $subscribed = true;
                        } else {
                            $subscribed = false;
                        }
                        break;
                    case 'gender':
                        $customer_data['gender'] = $this->getCustomerGenderName($value);
                        break;
                    case 'website_id':
                        $has_website_store_change = true;
                        $website_name = $value;
                        break;
                    case 'store_group_id':
                        $has_website_store_change = true;
                        $store_group_name = $value;
                        break;
                    case 'store_id':
                        $has_website_store_change = true;
                        $store_name = $value;
                        break;
                    default:
                        $customer_data[$customerKeys[$key]] = $value;
                }
                if (key_exists($key, $customerBillingKeys)) {
                    switch ($customerBillingKeys[$key]) {
                        case 'prefix':
                            if (!key_exists($key, $customer_data) || $customer_data[$key] == '') {
                                $customer_data['prefix'] = $value;
                            }
                            break;
                        case 'firstname':
                            if (!key_exists($key, $customer_data) || $customer_data[$key] == '') {
                                $customer_data['firstname'] = $value;
                            }
                            break;
                        case 'middlename':
                            if (!key_exists($key, $customer_data) || $customer_data[$key] == '') {
                                $customer_data['middlename'] = $value;
                            }
                            break;
                        case 'lastname':
                            if (!key_exists($key, $customer_data) || $customer_data[$key] == '') {
                                $customer_data['lastname'] = $value;
                            }
                            break;
                        case 'suffix':
                            if (!key_exists($key, $customer_data) || $customer_data[$key] == '') {
                                $customer_data['suffix'] = $value;
                            }
                            break;
                    }
                }
            } else if (key_exists($key, $customerBillingKeys) && $customerBillingKeys[$key] != '') {
                switch ($customerBillingKeys[$key]) {
                    case 'country_id':
                        $country_id = $this->searchCountry($value);
                        $customer_billing_data['country_id'] = $country_id;
                        if (!is_null($regions)) {
                            if (is_array($regions)) {
                                $customer_billing_data['region_id'] = $regions[$country_id];
                            } else {
                                $customer_billing_data['region_id'] = $regions;
                            }
                        }
                        break;
                    case 'region':
                        $customer_billing_data['region'] = $value;
                        if ($country_id != '') {
                            $region = $this->searchRegionId($value, $country_id);
                            if ($region != $value) {
                                $customer_billing_data['region_id'] = $region;
                            }
                        } else {
                            $regions = $this->searchRegionId($value);
                        }
                        break;
                    default:
                        $customer_billing_data[$customerBillingKeys[$key]] = $value;
                }
            } else if (key_exists($key, $customerShippingKeys) && $customerShippingKeys[$key] != '') {
                switch ($customerShippingKeys[$key]) {
                    case 'country_id':
                        $country_id = $this->searchCountry($value);
                        $customer_shipping_data['country_id'] = $country_id;
                        if (!is_null($regions)) {
                            if (is_array($regions)) {
                                $customer_shipping_data['region_id'] = $regions[$country_id];
                            } else {
                                $customer_shipping_data['region_id'] = $regions;
                            }
                        }
                        break;
                    case 'region':
                        $customer_shipping_data['region'] = $value;
                        if ($country_id != '') {
                            $region = $this->searchRegionId($value, $country_id);
                            if ($region != $value) {
                                $customer_shipping_data['region_id'] = $region;
                            }
                        } else {
                            $regions = $this->searchRegionId($value);
                        }
                        break;
                    default:
                        $customer_shipping_data[$customerShippingKeys[$key]] = $value;
                }
            }
            if ($key == 'accountname') {
                $company = $value;
            }
        }

        $this->_vtiger_model = 'Contacts';
        $this->_function = 'getAllByAccount';
        $postData = array(
            'accountid' => $vtigerId
        );
        $contactsResult = $this->post($postData);

        $contactsResult = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($contactsResult));
        $contactsRows = $contactsResult['crm4ecommerce'];
        $contacts = array();
        $contactsByAddressId = array();
        $address_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_CONTACT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ADDRESS_INFO);

        $vtiger_billing = '';
        $vtiger_shipping = '';
        $firstname = '';
        $lastname = '';
        $email = '';
        $telephone = '';
        
        if (is_array($contactsRows)) {
            foreach ($contactsRows as $_k => $_contact) {
                $contact = array();
                $is_billing = true;
                $is_shipping = true;
                foreach ($address_info_mapping as $field) {
                    if (key_exists($field->getVtigerColumn(), $_contact)) {
                        $contact[$field->getAttributeCode()] = $_contact[$field->getVtigerColumn()];
                        if ($field->getAttributeCode() == 'country_id') {
                            $country_id = $this->searchCountry($_contact[$field->getVtigerColumn()]);
                            $contact['country_id'] = $country_id;
                        }
                        if ($vtiger_billing == '' && $is_billing && key_exists($field->getAttributeCode(), $customer_billing_data)
                                && $customer_billing_data[$field->getAttributeCode()] != $contact[$field->getAttributeCode()]) {
                            $is_billing = false;
                        }
                        if ($vtiger_shipping == '' && $is_shipping && key_exists($field->getAttributeCode(), $customer_shipping_data)
                                && $customer_shipping_data[$field->getAttributeCode()] != $contact[$field->getAttributeCode()]) {
                            $is_shipping = false;
                        }
                    }
                }
                if ($firstname == '' && $contact['firstname'] != '') {
                    $firstname = $contact['firstname'];
                }
                if ($lastname == '' && $contact['lastname'] != '') {
                    $lastname = $contact['lastname'];
                }
                if ($telephone == '' && $contact['telephone'] != '') {
                    $telephone = $contact['telephone'];
                }
                if ($vtiger_billing == '' && $is_billing) {
                    $vtiger_billing = $_contact['contactid'];
                }
                if ($vtiger_shipping == '' && $is_shipping) {
                    $vtiger_shipping = $_contact['contactid'];
                }
                $contacts[$_contact['contactid']] = $contact;
                $contactsByAddressId[$_contact['remote_id']] = $_contact['contactid'];
            }
        }

        if ($firstname == '' && $customer_data['firstname'] != '') {
            $firstname = $customer_data['firstname'];
        }
        if ($lastname == '' && $customer_data['lastname'] != '') {
            $lastname = $customer_data['lastname'];
        }

        if (!isset($customer_data['email']) || $customer_data['email'] == '') {
            $customer_data['email'] = str_replace('{{vtiger_id}}', $vtigerId, Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/account_default_email'));
        }
        $customer_data['vtiger_id'] = $vtigerId;
        $customer_data['vtiger_type'] = 'Accounts';
        $customer = Mage::getModel('customer/customer')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$customer->getId() && (int) $customer_id > 0) {
            $customer = Mage::getModel('customer/customer')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $customer_id))
                    ->getFirstItem();
        }
        if (!$customer->getId() && isset($customer_data['email']) && $customer_data['email'] != '') {
            $customer = Mage::getModel('customer/customer')->getCollection()
                    ->addFieldToFilter('email', array('eq' => $customer_data['email']))
                    ->getFirstItem();
        }

        if ($customer->getId() > 0) {
            $customer = Mage::getModel('customer/customer')->load($customer->getId());
            if ($has_website_store_change) {
                $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name);
                if ($storeId) {
                    $storeIds = explode(',', $storeId);
                    $customer_data['website_id'] = $storeIds[0];
                    $customer_data['store_id'] = $storeIds[2];
                    $customer_data['created_in'] = Mage::getModel('core/store')->load($storeIds[2])->getName();
                }
            }

            $flg_billing = false;
            foreach ($customer_billing_data as $k => $v) {
                if (trim($v) != '') {
                    $flg_billing = true;
                    break;
                }
            }
            $flg_shipping = false;
            foreach ($customer_shipping_data as $k => $v) {
                if (trim($v) != '') {
                    $flg_shipping = true;
                    break;
                }
            }
            $account_name_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/account_name_format');
            if ($account_name_format == '') {
                $account_name_format = '{{company}} (#{{customer_id}})';
            }
            $account_name_format = str_replace('{{customer_id}}', $customer->getId(), $account_name_format);
            $account_name_format = str_replace('{{fullname}}', $customer->getFirstname() . ' ' . $customer->getLastname(), $account_name_format);
            $account_name_format = explode('{{company}}', $account_name_format);
            $company = str_replace('!@#$%^' . $account_name_format[0], '', '!@#$%^' . $company);
            $company = str_replace($account_name_format[1] . '!@#$%^', '', $company . '!@#$%^');
            $company = trim($company, '!@#$%^');
            if (str_replace($customer->getFirstname() . ' ' . $customer->getLastname(), '', $company) == $company) {
                $this->saveAccountName($customer->getId(), $company);
                $customer_billing_data['company'] = $company;
            } else {
                $customer_billing_data['company'] = '';
            }
            $new_billing_id = null;
            $new_shipping_id = null;

            Mage::getModel('core/session')->setData('remote', true);
            if (is_array($contactsRows)) {
                $listAdresses = $customer->getAddresses();
                foreach ($listAdresses as $address) {
                    $address = Mage::getModel('customer/address')->load($address->getId());
                    if ($address->getVtigerId() != '') {
                        if (key_exists($address->getVtigerId(), $contacts)) {
                            $address->addData($contacts[$address->getVtigerId()])
                                    ->setCompany($customer_billing_data['company']);
                            unset($contacts[$address->getVtigerId()]);
                        } else if (key_exists($address->getId(), $contactsByAddressId)) {
                            $address->addData($contacts[$contactsByAddressId[$address->getId()]])
                                    ->setCompany($customer_billing_data['company']);
                            unset($contacts[$contactsByAddressId[$address->getId()]]);
                        } else {
                            $address->setCustomerId(null);
                        }
                    }
                    if ($vtiger_billing != '' && $address->getVtigerId() == $vtiger_billing) {
                        $new_billing_id = $address->getId();
                    } else if ($vtiger_billing == '' && $customer->getDefaultBilling() == $address->getId()) {
                        $flg_billing = false;
                        $address->addData($customer_billing_data);
                    }
                    if ($vtiger_shipping != '' && $address->getVtigerId() == $vtiger_shipping) {
                        $new_shipping_id = $address->getId();
                    } else if ($vtiger_shipping == '' && $customer->getDefaultShipping() == $address->getId()) {
                        $flg_billing = false;
                        $address->addData($customer_shipping_data);
                    }
                    $address->save();
                }
                foreach ($contacts as $contactid => $contact_info) {
                    $address = Mage::getModel('customer/address')->getCollection()
                                    ->addFieldToFilter('vtiger_id', $contactid)->getFirstItem();
                    if ($address->getId() > 0) {
                        $this->addressChangeCustomerId($address->getId(), $customer->getId());
                        $address = Mage::getModel('customer/address')->load($address->getId());
                        $address->addData($contacts[$address->getVtigerId()])->save();
                    } else {
                        $address = Mage::getModel('customer/address')->setData($contact_info)
                                        ->setVtigerId($contactid)
                                        ->setCustomerId($customer->getId())->save();
                    }
                    if ($vtiger_billing != '' && $contactid == $vtiger_billing) {
                        $new_billing_id = $address->getId();
                    }
                    if ($vtiger_shipping != '' && $contactid == $vtiger_shipping) {
                        $new_shipping_id = $address->getId();
                    }
                }
            }
            if ($vtiger_billing == '' && $flg_billing) {
                if (!key_exists('firstname', $customer_billing_data) || $customer_billing_data['firstname'] == '') {
                    if ($firstname == '') {
                        $firstname = $customer->getFirstname();
                    }
                    if ($firstname == '') {
                        $firstname = Mage::helper('vtigersynchronization')->__('Undefined');
                    }
                    $customer_billing_data['firstname'] = $firstname;
                }
                if (!key_exists('lastname', $customer_billing_data) || $customer_billing_data['lastname'] == '') {
                    if ($lastname == '') {
                        $lastname = $customer->getLastname();
                    }
                    if ($lastname == '') {
                        $lastname = Mage::helper('vtigersynchronization')->__('Undefined');
                    }
                    $customer_billing_data['lastname'] = $lastname;
                }
                if (!key_exists('telephone', $customer_billing_data) || $customer_billing_data['telephone'] == '') {
                    if ($telephone != '') {
                        $customer_billing_data['telephone'] = $telephone;
                    } else {
                        $customer_billing_data['telephone'] = Mage::helper('vtigersynchronization')->__('Undefined');
                    }
                }
                $new_billing_id = Mage::getModel('customer/address')->setData($customer_billing_data)
                                ->setCustomerId($customer->getId())->save()->getId();
            }
            if ($vtiger_shipping == '' && $flg_shipping) {
                $is_same = true;
                foreach ($customer_shipping_data as $k => $v) {
                    if ($v != $customer_billing_data[$k]) {
                        $is_same = false;
                        break;
                    }
                }
                if (!$is_same) {
                    if (!key_exists('firstname', $customer_shipping_data) || $customer_shipping_data['firstname'] == '') {
                        if ($firstname == '') {
                            $firstname = $customer->getFirstname();
                        }
                        if ($firstname == '') {
                            $firstname = Mage::helper('vtigersynchronization')->__('Undefined');
                        }
                        $customer_shipping_data['firstname'] = $firstname;
                    }
                    if (!key_exists('lastname', $customer_shipping_data) || $customer_shipping_data['lastname'] == '') {
                        if ($lastname == '') {
                            $lastname = $customer->getLastname();
                        }
                        if ($lastname == '') {
                            $lastname = Mage::helper('vtigersynchronization')->__('Undefined');
                        }
                        $customer_shipping_data['lastname'] = $lastname;
                    }
                    if (!key_exists('telephone', $customer_shipping_data) || $customer_shipping_data['telephone'] == '') {
                        if ($telephone != '') {
                            $customer_shipping_data['telephone'] = $telephone;
                        } else {
                            $customer_shipping_data['telephone'] = Mage::helper('vtigersynchronization')->__('Undefined');
                        }
                    }
                    $new_shipping_id = Mage::getModel('customer/address')->setData($customer_shipping_data)
                                    ->setCustomerId($customer->getId())->save()->getId();
                } else if (!is_null($new_billing_id)) {
                    $new_shipping_id = $new_billing_id;
                }
            }

            if (!is_null($new_billing_id)) {
                $customer->setDefaultBilling($new_billing_id);
            }
            if (!is_null($new_shipping_id)) {
                $customer->setDefaultShipping($new_shipping_id);
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($customer->getId())
                    ->setToId($customer->getId())
                    ->setNumberSuccess(1)->setSuccessIds($customer->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($customer->getId(), $customer->getFirstname() . ' ' . $customer->getLastname() . ' (' . $customer->getEmail() . ')')->save();

            $customer->addData($customer_data);
            if (!is_null($subscribed)) {
                $customer->setIsSubscribed($subscribed);
                if ($subscribed) {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED)->save();
                } else {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED)->save();
                }
            }
            $customer->save();

            $wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer->getId(), true);
            $wishListItemCollection = $wishList->getItemCollection();
            foreach ($account['ref_products'] as $_item => $productid) {
                $flag = false;
                if (count($wishListItemCollection) > 0) {
                    foreach ($wishListItemCollection as $item) {
                        if ($productid == $item->getProduct()->getId()) {
                            $flag = true;
                            break;
                        }
                    }
                }
                if (!$flag) {
                    $wishList->addNewItem(Mage::getModel('catalog/product')->load($productid));
                }
            }
            if (count($wishListItemCollection) > 0) {
                foreach ($wishListItemCollection as $item) {
                    $flag = false;
                    $_id = $item->getProduct()->getId();
                    foreach ($account['ref_products'] as $_item => $productid) {
                        if ($productid == $_id) {
                            $flag = true;
                            break;
                        }
                    }
                    if (!$flag) {
                        $item = Mage::getModel('wishlist/item')->load($item->getId());
                        $item->delete();
                    }
                }
            }
            $wishList->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer %s (%s) have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                ), $customer->getEmail()
                        ) . '<br/>';
            } else {
                return $customer->getId();
            }
        } else {
            $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name, $storeId);
            $storeIds = explode(',', $storeId);
            $customer_data['website_id'] = $storeIds[0];
            $customer_data['store_id'] = $storeIds[2];
            $customer_data['created_in'] = Mage::getModel('core/store')->load($storeIds[2])->getName();

            if (!key_exists('firstname', $customer_data) || $customer_data['firstname'] == '') {
                if ($firstname != '') {
                    $customer_data['firstname'] = $firstname;
                } else {
                    $customer_data['firstname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('lastname', $customer_data) || $customer_data['lastname'] == '') {
                if ($lastname != '') {
                    $customer_data['lastname'] = $lastname;
                } else {
                    $customer_data['lastname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('email', $customer_data) || $customer_data['email'] == '') {
                if ($email != '') {
                    $customer_data['email'] = $email;
                }
            }
            Mage::getModel('core/session')->setData('remote', true);
            $customer_data['vtiger_accountname'] = $company;
            $customer = Mage::getModel('customer/customer')
                    ->addData($customer_data);

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($customer->getId())
                    ->setToId($customer->getId())
                    ->setNumberSuccess(1)->setSuccessIds($customer->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($customer->getId(), $customer->getFirstname() . ' ' . $customer->getLastname() . ' (' . $customer->getEmail() . ')')->save();
            $customer->save();
            Mage::getModel('core/session')->setData('company', $company);

            $customer = Mage::getModel('customer/customer')->load($customer->getId());

            $flg_billing = false;
            foreach ($customer_billing_data as $k => $v) {
                if (trim($v) != '') {
                    $flg_billing = true;
                    break;
                }
            }
            $flg_shipping = false;
            foreach ($customer_shipping_data as $k => $v) {
                if (trim($v) != '') {
                    $flg_shipping = true;
                    break;
                }
            }

            $account_name_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/account_name_format');
            if ($account_name_format == '') {
                $account_name_format = '{{company}} (#{{customer_id}})';
            }
            $account_name_format = str_replace('{{customer_id}}', $customer->getId(), $account_name_format);
            $account_name_format = str_replace('{{fullname}}', $customer->getFirstname() . ' ' . $customer->getLastname(), $account_name_format);
            $account_name_format = explode('{{company}}', $account_name_format);
            $company = str_replace('!@#$%^' . $account_name_format[0], '', '!@#$%^' . $company);
            $company = str_replace($account_name_format[1] . '!@#$%^', '', $company . '!@#$%^');
            $company = trim($company, '!@#$%^');

            if (!key_exists('firstname', $customer_billing_data) || $customer_billing_data['firstname'] == '') {
                if ($firstname != '') {
                    $customer_billing_data['firstname'] = $firstname;
                } else {
                    $customer_billing_data['firstname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('lastname', $customer_billing_data) || $customer_billing_data['lastname'] == '') {
                if ($lastname != '') {
                    $customer_billing_data['lastname'] = $lastname;
                } else {
                    $customer_billing_data['lastname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('telephone', $customer_billing_data) || $customer_billing_data['telephone'] == '') {
                if ($telephone != '') {
                    $customer_billing_data['telephone'] = $telephone;
                } else {
                    $customer_billing_data['telephone'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }

            if (!key_exists('firstname', $customer_shipping_data) || $customer_shipping_data['firstname'] == '') {
                if ($firstname != '') {
                    $customer_shipping_data['firstname'] = $firstname;
                } else {
                    $customer_shipping_data['firstname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('lastname', $customer_shipping_data) || $customer_shipping_data['lastname'] == '') {
                if ($lastname != '') {
                    $customer_shipping_data['lastname'] = $lastname;
                } else {
                    $customer_shipping_data['lastname'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }
            if (!key_exists('telephone', $customer_shipping_data) || $customer_shipping_data['telephone'] == '') {
                if ($telephone != '') {
                    $customer_shipping_data['telephone'] = $telephone;
                } else {
                    $customer_shipping_data['telephone'] = Mage::helper('vtigersynchronization')->__('Undefined');
                }
            }

            $new_billing_id = null;
            $new_shipping_id = null;
            if (is_array($contactsRows)) {
                foreach ($contacts as $contactid => $contact_info) {
                    $id = Mage::getModel('customer/address')->setData($contact_info)
                                    ->setVtigerId($contactid)
                                    ->setCustomerId($customer->getId())->save();

                    if ($vtiger_billing != '' && $vtiger_billing == $contactid) {
                        $new_billing_id = $id;
                    }
                    if ($vtiger_shipping != '' && $vtiger_shipping == $contactid) {
                        $new_shipping_id = $id;
                    }
                }
            }
            if ($vtiger_billing == '' && $flg_billing) {
                $billing = Mage::getModel('customer/address')->setData($customer_billing_data)
                                ->setCustomerId($customer->getId())->save();
                $new_billing_id = $billing->getId();
            }
            if ($vtiger_shipping == '' && $flg_shipping) {
                $is_same = true;
                foreach ($customer_shipping_data as $k => $v) {
                    if ($v != $customer_billing_data[$k]) {
                        $is_same = false;
                        break;
                    }
                }
                if (!$is_same) {
                    $shipping = Mage::getModel('customer/address')->setData($customer_shipping_data)
                                    ->setCustomerId($customer->getId())->save();
                    $new_shipping_id = $shipping->getId();
                } else if (!is_null($new_billing_id)) {
                    $new_shipping_id = $new_billing_id;
                }
            }

            if (!is_null($new_billing_id)) {
                $customer->setDefaultBilling($new_billing_id);
            }
            if (!is_null($new_shipping_id)) {
                $customer->setDefaultShipping($new_shipping_id);
            }

            if (!key_exists('group_id', $customer_data) || $customer_data['group_id'] == '') {
                $customer->setGroupId(Mage::getStoreConfig('customer/create_account/default_group'));
            }
            if (!is_null($subscribed)) {
                $customer->setIsSubscribed($subscribed);
                if ($subscribed) {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED)->save();
                } else {
                    Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED)->save();
                }
            }
            $customer->save();
            $customer->sendPasswordReminderEmail();

            $wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer->getId(), true);
            $wishListItemCollection = $wishList->getItemCollection();

            foreach ($account['ref_products'] as $_item => $productid) {
                $flag = false;
                if (count($wishListItemCollection) > 0) {
                    foreach ($wishListItemCollection as $item) {
                        if ($productid == $item->getProduct()->getId()) {
                            $flag = true;
                            break;
                        }
                    }
                }
                if (!$flag) {
                    $wishList->addNewItem(Mage::getModel('catalog/product')->load($productid));
                }
            }
            if (count($wishListItemCollection) > 0) {
                foreach ($wishListItemCollection as $item) {
                    $flag = false;
                    $_id = $item->getProduct()->getId();
                    foreach ($account['ref_products'] as $_item => $productid) {
                        if ($productid == $_id) {
                            $flag = true;
                            break;
                        }
                    }
                    if (!$flag) {
                        $item = Mage::getModel('wishlist/item')->load($item->getId());
                        $item->delete();
                    }
                }
            }
            $wishList->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer %s (%s) have been created new successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                ), $customer->getEmail()
                        ) . '<br/>';
            } else {
                return $customer->getId();
            }
        }
    }

    public function remoteContacts($vtigerId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . $vtigerId . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $contact = $data['crm4ecommerce'];
        $address_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_CUSTOMER_VTIGER_CONTACT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ADDRESS_INFO);
        $addressData = array();
        foreach ($address_info_mapping as $field) {
            $addressData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $customer_address_data = array();
        $customer = null;
        $address_id = 0;
        foreach ($contact as $key => $value) {
            $value = ($value == '' || (string) $value == '0') ? null : $value;
            if ($key == 'remote_id') {
                $address_id = $value;
                continue;
            }
            if (key_exists($key, $addressData) && $addressData[$key] != '') {
                $customer_address_data[$addressData[$key]] = $value;
                switch ($addressData[$key]) {
                    case 'country_id':
                        $country_id = $this->searchCountry($value);
                        $customer_address_data['country_id'] = $country_id;
                        if (!is_null($regions)) {
                            if (is_array($regions)) {
                                $customer_address_data['region_id'] = $regions[$country_id];
                            } else {
                                $customer_address_data['region_id'] = $regions;
                            }
                        }
                        break;
                    case 'region':
                        $customer_address_data['region'] = $value;
                        if ($country_id != '') {
                            $region = $this->searchRegionId($value, $country_id);
                            if ($region != $value) {
                                $customer_address_data['region_id'] = $region;
                            }
                        } else {
                            $regions = $this->searchRegionId($value);
                        }
                        break;
                }
            }
            if ($key == 'account_id') {
                $_customer = Mage::getModel('customer/customer')->getCollection()
                        ->addFieldToFilter('vtiger_id', $value)
                        ->getFirstItem();
                if ($_customer->getId() > 0) {
                    $customer = Mage::getModel('customer/customer')->load($_customer->getId());
                }
            }
        }

        $customer_address_data['vtiger_id'] = $vtigerId;
        $address = Mage::getModel('customer/address')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$address->getId() && (int) $address_id > 0) {
            $address = Mage::getModel('customer/address')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $address_id))
                    ->getFirstItem();
        }

        if ($address->getId() > 0) {
            $this->addressChangeCustomerId($address->getId(), $customer->getId());
            $address = Mage::getModel('customer/address')->load($address->getId());
            $address->addData($customer_address_data);

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER_ADDRESS)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($address->getId())
                    ->setToId($address->getId())
                    ->setNumberSuccess(1)->setSuccessIds($address->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($address->getId(), $address->getFirstname() . ' ' . $address->getLastname() . ' (' . $address->getCustomer()->getEmail() . ')')->save();
            $address->save();

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer\'s Address has id %s (of customer %s) have been updated successfully.', $address->getId(), sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                )
                        ) . '<br/>';
            } else {
                return $address->getId();
            }
        } else {
            $address = Mage::getModel('customer/address')->addData($customer_address_data)->setCustomerId($customer->getId());

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::CUSTOMER_ADDRESS)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($address->getId())
                    ->setToId($address->getId())
                    ->setNumberSuccess(1)->setSuccessIds($address->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($address->getId(), $address->getFirstname() . ' ' . $address->getLastname() . ' (' . $address->getCustomer()->getEmail() . ')')->save();
            $address->save();

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Customer\'s Address has id %s (of customer %s) have been created new successfully.', $address->getId(), sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/customer/edit', array('id' => $customer->getId())), $customer->getFirstname() . ' ' . $customer->getLastname()
                                )
                        ) . '<br/>';
            } else {
                return $address->getId();
            }
        }
    }

    private function addressChangeCustomerId($address_id, $customer_id) {
        $coreResource = Mage::getSingleton('core/resource');
        $sql = "UPDATE `" . $coreResource->getTableName('customer_address_entity')
                . "` SET `parent_id` = '" . $customer_id . "'"
                . " WHERE `entity_id` = " . $address_id;

        $write = $coreResource->getConnection('core_write');
        $write->query($sql);
    }

    private function saveAccountName($customer_id, $account_name) {
        $coreResource = Mage::getSingleton('core/resource');
        $sql = "UPDATE `" . $coreResource->getTableName('customer_entity')
                . "` SET `vtiger_accountname` = '" . $account_name . "'"
                . " WHERE `entity_id` = " . $customer_id;

        $write = $coreResource->getConnection('core_write');
        $write->query($sql);
    }

    private function searchShippingMethod($shipping_method_name) {
        $methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
        foreach ($methods as $_ccode => $_carrier) {
            $_methods = $_carrier->getAllowedMethods();
            if ($_methods) {
                $_title = Mage::getStoreConfig("carriers/$_ccode/title");
                if (!$_title) {
                    $_title = $_ccode;
                }
                foreach ($_methods as $_mcode => $_method) {
                    if ($shipping_method_name == $_title . ' - ' . $_method) {
                        return $_ccode . '_' . $_mcode;
                    }
                }
            }
        }
        return '';
    }

    private function searchCountry($countryName) {
        $collection = Mage::getModel('directory/country')->getCollection();
        foreach ($collection as $country) {
            if ($country->getName() == $countryName) {
                return $country->getId();
            }
        }
    }

    private function searchProductVisibilityLabel($value) {
        $array = Mage::getModel('catalog/product_visibility')->getOptionArray();
        foreach ($array as $k => $v) {
            if ($value == $v) {
                return $k;
            }
        }
        return '';
    }

    private function searchWebsiteId($name) {
        $websites = Mage::getModel('core/website')->getCollection();
        foreach ($websites as $website) {
            if ($website->getName() == $name) {
                return $website->getId();
            }
        }
        return 0;
    }

    public function searchStoreId($website_name, $store_group_name, $store_name, $default = null) {
        $admin_store = Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID);
        if ($store_name == $admin_store->getName()) {
            $websites = Mage::getModel('core/website')->getCollection();
            $website_id = 0;
            foreach ($websites as $website) {
                if ($website_name == '' || $website->getName() == $website_name) {
                    $website_id = $website->getId();
                    break;
                }
            }
            return $website_id . ',' . $admin_store->getGroup()->getId() . ',' . $admin_store->getId();
        } else {
            $stores = Mage::getModel('core/store')->getCollection();
            $store_id = 0;
            $store_group_id = 0;
            $website_id = 0;
            $_store = null;
            foreach ($stores as $store) {
                if ($store_name == '' || $store->getName() == $store_name) {
                    $_store = $store;
                    $store_id = $store->getId();
                    $store_group = $store->getGroup();
                    if ($store_group_name == '' || $store_group->getName() == $store_group_name) {
                        $store_group_id = $store_group->getId();
                        $website = $store_group->getWebsite();
                        if ($website_name == '' || $website->getName() == $website_name) {
                            $website_id = $website->getId();
                            break;
                        }
                    }
                }
            }
            if (!$store_id) {
                return $default;
            } else {
                if (!$store_group_id) {
                    return $_store->getWebsiteId() . ',' . $_store->getGroupId() . ',' . $store_id;
                } else {
                    return $website_id . ',' . $store_group_id . ',' . $store_id;
                }
            }
        }
    }

    private function searchRegionId($regionName, $country_id = null) {
        if (!is_null($country_id)) {
            $region = Mage::getModel('directory/region')->loadByName($regionName, $country_id);
            if ($region->getId() > 0) {
                return $region->getId();
            }
        } else {
            $rs = Mage::getModel('directory/region')->getCollection()
                    ->addFieldToFilter('name', $regionName);
            $regions = array();
            foreach ($rs as $r) {
                $regions[$r->getCountryId()] = $r->getId();
            }
            if (count($regions) > 0) {
                return $regions;
            }
        }
        return '';
    }

    private function searchAttribute($attribute_code, $attribute_label) {
        $resource = Mage::getSingleton("core/resource");
        $read = $resource->getConnection("core_read");
        $select = $read->select()
                ->from(
                        array('eao' => Mage::getModel('core/resource')->getTableName('eav_attribute_option')), array('value' => 'option_id', 'label' => 'eaov.value')
                )
                ->join(
                        array('ea' => Mage::getModel('core/resource')->getTableName('eav_attribute')), 'eao.attribute_id=ea.attribute_id', array()
                )
                ->join(
                        array('eaov' => Mage::getModel('core/resource')->getTableName('eav_attribute_option_value')), 'eao.option_id=eaov.option_id', array()
                )
                ->where('ea.attribute_code=?', $attribute_code)
                ->where('eaov.store_id=0')
                ->order('label asc')
        ;
        $list_options = $read->fetchAll($select);

        foreach ($list_options as $option) {
            if ($option['label'] == $attribute_label) {
                return $option['value'];
            }
        }
        return null;
    }

    public function remoteProductImages($product_id, $data) {
        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $image = $data['crm4ecommerce'];
        $product_id = $image['product_id'];
        $name = $image['image_name'];
        $label = $image['image_label'];

        $attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', 'media_gallery');
        $product = Mage::getModel('catalog/product')->setStoreId(0)->load($product_id);
        $id = 0;

        foreach ($product->getMediaGallery('images') as $_image) {
            if ('/' . $name[0] . '/' . ($name[1] == '.' ? '_' : $name[1]) . '/' . $name == $_image['file']) {
                $id = $_image['value_id'];
            }
        }
        if ((int) $id == 0) {
            $coreResource = Mage::getSingleton('core/resource');
            $write = $coreResource->getConnection('core_write');
            $sql = "INSERT INTO `" . $coreResource->getTableName('catalog_product_entity_media_gallery')
                    . "` SET `attribute_id` = :attribute_id, `entity_id` = :entity_id, `value` = :value";
            $binds = array(
                'attribute_id' => $attributeId,
                'entity_id' => $product_id,
                'value' => '/' . $name[0] . '/' . ($name[1] == '.' ? '_' : $name[1]) . '/' . $name
            );
            $write->query($sql, $binds);

            $read = $coreResource->getConnection('core_read');
            $sql = "SELECT MAX(`value_id`) as 'max_value_id' FROM `" . $coreResource->getTableName('catalog_product_entity_media_gallery') . "`";
            $rs = $read->fetchAll($sql);
            $max_value_id = 0;
            foreach ($rs as $row) {
                $max_value_id = $row['max_value_id'];
            }
            if (!((int) $max_value_id > 0)) {
                $max_value_id = 0;
            }

            $sql = "SELECT MAX(`position`) + 1 as 'max_position' FROM `" . $coreResource->getTableName('catalog_product_entity_media_gallery_value')
                    . "` WHERE value_id IN (SELECT `value_id` FROM `" . $coreResource->getTableName('catalog_product_entity_media_gallery') . "` WHERE `entity_id` = " . $product_id . ")";
            $rs = $read->fetchAll($sql);
            $max_position = 0;
            foreach ($rs as $row) {
                $max_position = $row['max_position'];
            }
            if (!((int) $max_position > 0)) {
                $max_position = 0;
            }

            $sql = "INSERT INTO `" . $coreResource->getTableName('catalog_product_entity_media_gallery_value')
                    . "` SET `value_id` = :value_id, `label` = :label, `position` = :position";
            $binds = array(
                'value_id' => $max_value_id,
                'label' => $label,
                'position' => $max_position
            );
            $write->query($sql, $binds);
        } else {
            $coreResource = Mage::getSingleton('core/resource');
            $sql = "UPDATE `" . $coreResource->getTableName('catalog_product_entity_media_gallery_value')
                    . "` SET `label` = :label WHERE `value_id` = :value_id";
            $write = $coreResource->getConnection('core_write');
            $binds = array(
                'label' => $label,
                'value_id' => $id
            );
            $write->query($sql, $binds);
        }
        $source = $image['image_data'];
        $source = str_replace(' ', '+', $source);
        $source = base64_decode($image['image_data']);
        $dir = Mage::getBaseDir() . DS . 'media' . DS . 'catalog' . DS . 'product' . DS;
        $folder = $name[0] . DS . ($name[1] == '.' ? '_' : $name[1]);
        $filename = $dir . $folder . DS . $name;

        if (!file_exists($filename)) {
            if (!is_dir($dir . $name[0])) {
                mkdir($dir . $name[0]);
            }
            if (!is_dir($dir . $folder)) {
                mkdir($dir . $folder);
            }
            file_put_contents($filename, $source);
        }
    }

    public function prepareTierPrice($tiers, $product_id = null) {
        if ($tiers != null && $tiers != '') {
            $_tiers = explode("\n", $tiers);
            $tiers = array();

            $coreResource = Mage::getSingleton('core/resource');
            $read = $coreResource->getConnection('core_read');
            $sql = "SELECT MAX(`customer_group_id`) + 1 as 'max_id' FROM `" . $coreResource->getTableName('customer_group') . "`";
            $rs = $read->fetchAll($sql);
            $max_id = 0;
            foreach ($rs as $row) {
                $max_id = $row['max_id'];
            }

            foreach ($_tiers as $_tier) {
                if ($_tier != '') {
                    $p = explode('-', $_tier);
                    if (count($p) < 4) {
                        continue;
                    }
                    $price_qty = explode('>=', $p[2]);
                    $price = explode(':', $p[3]);
                    $price = preg_replace('/(^[^0-9.,]+)|([^0-9.,]+)$/', '', $price[1]);
                    $group_id = $this->getCustomerGroupCode(trim($p[1]));
                    $_p = array(
                        'website_id' => (string) $this->searchWebsiteId(trim($p[0])),
                        'all_groups' => $group_id > $max_id ? '1' : '0',
                        'cust_group' => (string) $group_id,
                        'price_qty' => trim($price_qty[1]),
                        'price' => $price
                    );
                    $tiers[] = $_p;
                }
            }
        }
        $p_tier_price = array();
        if ($product_id != null && (int) $product_id > 0) {
            $resource = Mage::getSingleton('core/resource');
            $read = $resource->getConnection('core_read');
            $select = 'SELECT * FROM `' . $resource->getTableName('catalog_product_entity_tier_price') . '` WHERE entity_id = ' . $product_id;
            $rs = $read->fetchAll($select);
            foreach ($rs as $row) {
                $p_tier_price[] = array(
                    'price_id' => $row['value_id'],
                    'website_id' => $row['website_id'],
                    'all_groups' => $row['all_groups'],
                    'cust_group' => $row['customer_group_id'],
                    'price_qty' => $row['qty'],
                    'price' => $row['value']
                );
            }
        }
        if ($tiers != null && is_array($tiers)) {
            for ($i = 0; $i < count($p_tier_price); $i++) {
                for ($j = 0; $j < count($tiers); $j++) {
                    if (isset($tiers[$j]['price_id']) && $tiers[$j]['price_id'] != '') {
                        continue;
                    }
                    if ($tiers[$j]['website_id'] == $p_tier_price[$i]['website_id'] &&
                            $tiers[$j]['all_groups'] == $p_tier_price[$i]['all_groups'] &&
                            $tiers[$j]['cust_group'] == $p_tier_price[$i]['cust_group'] &&
                            $tiers[$j]['price_qty'] == $p_tier_price[$i]['price_qty']) {
                        $tiers[$j]['price_id'] = $p_tier_price[$i]['price_id'];
                        $p_tier_price[$i]['price'] = $tiers[$j]['price'];
                        $p_tier_price[$i]['website_price'] = $tiers[$j]['price'];
                        $p_tier_price[$i]['delete'] = '0';
                        break;
                    }
                }
            }
            $i = 0;
            for (; $i < count($p_tier_price); $i++) {
                if (isset($p_tier_price[$i]['delete']) && $p_tier_price[$i]['delete'] == '0') {
                    continue;
                }
                $flg = false;
                for ($j = 0; $j < count($tiers); $j++) {
                    if (!$flg) {
                        if (isset($tiers[$j]['price_id']) && $tiers[$j]['price_id'] != '') {
                            continue;
                        }

                        $flg = true;
                        $tiers[$j]['price_id'] = $p_tier_price[$i]['price_id'];
                        foreach ($tiers[$j] as $k => $v) {
                            $p_tier_price[$i][$k] = $v;
                        }
                    }
                }
                if ($flg) {
                    $p_tier_price[$i]['delete'] = '0';
                } else {
                    $p_tier_price[$i]['delete'] = '1';
                }
            }
            for ($j = 0; $j < count($tiers); $j++) {
                if (isset($tiers[$j]['price_id']) && $tiers[$j]['price_id'] != '') {
                    continue;
                }
                $p_tier_price[$i] = array();
                foreach ($tiers[$j] as $k => $v) {
                    $p_tier_price[$i][$k] = $v;
                }
                $p_tier_price[$i]['delete'] = '0';
                $i++;
            }
        }
        if ($product_id != null && (int) $product_id > 0) {
            $resource = Mage::getSingleton('core/resource');
            $write = $resource->getConnection('core_write');
            foreach ($p_tier_price as $tier) {
                if (isset($tier['price_id']) && (int) $tier['price_id'] > 0) {
                    if ($tier['delete'] == '1') {
                        $sql = "DELETE FROM `" . $resource->getTableName('catalog_product_entity_tier_price')
                                . "` WHERE `value_id` = :value_id";
                        $binds = array(
                            'value_id' => $tier['price_id']
                        );
                        $write->query($sql, $binds);
                    } else {
                        $sql = "UPDATE `" . $resource->getTableName('catalog_product_entity_tier_price')
                                . "` SET `entity_id` = :entity_id, `all_groups` = :all_groups, `customer_group_id` = :customer_group_id, `qty` = :qty, `value` = :value, `website_id` = :website_id WHERE `value_id` = :value_id";
                        $binds = array(
                            'entity_id' => $product_id,
                            'all_groups' => $tier['all_groups'],
                            'customer_group_id' => $tier['cust_group'],
                            'qty' => $tier['price_qty'],
                            'value' => $tier['price'],
                            'website_id' => $tier['website_id'],
                            'value_id' => $tier['price_id']
                        );
                        $write->query($sql, $binds);
                    }
                } else {
                    $sql = "INSERT INTO `" . $resource->getTableName('catalog_product_entity_tier_price')
                            . "` SET `entity_id` = :entity_id, `all_groups` = :all_groups, `customer_group_id` = :customer_group_id, `qty` = :qty, `value` = :value, `website_id` = :website_id";
                    $binds = array(
                        'entity_id' => $product_id,
                        'all_groups' => $tier['all_groups'],
                        'customer_group_id' => $tier['cust_group'],
                        'qty' => $tier['price_qty'],
                        'value' => $tier['price'],
                        'website_id' => $tier['website_id']
                    );
                    $write->query($sql, $binds);
                }
            }
        }
        return $p_tier_price;
    }

    public function prepareGroupPrice($groups, $product_id = null) {
        if ($groups != null && $groups != '') {
            $_groups = explode("\n", $groups);
            $groups = array();

            $coreResource = Mage::getSingleton('core/resource');
            $read = $coreResource->getConnection('core_read');
            $sql = "SELECT MAX(`customer_group_id`) + 1 as 'max_id' FROM `" . $coreResource->getTableName('customer_group') . "`";
            $rs = $read->fetchAll($sql);
            $max_id = 0;
            foreach ($rs as $row) {
                $max_id = $row['max_id'];
            }

            foreach ($_groups as $_group) {
                if (trim($_group) != '') {
                    $p = explode('-', $_group);
                    if (count($p) < 3) {
                        continue;
                    }
                    $price = explode(':', $p[2]);
                    $price = preg_replace('/(^[^0-9.,]+)|([^0-9.,]+)$/', '', $price[1]);
                    $group_id = $this->getCustomerGroupCode(trim($p[1]));
                    $_p = array(
                        'website_id' => (string) $this->searchWebsiteId(trim($p[0])),
                        'all_groups' => $group_id > $max_id ? '1' : '0',
                        'cust_group' => (string) $group_id,
                        'price' => $price
                    );
                    $groups[] = $_p;
                }
            }
        }
        $p_group_price = array();
        if ($product_id != null && (int) $product_id > 0) {
            $resource = Mage::getSingleton('core/resource');
            $read = $resource->getConnection('core_read');
            $select = 'SELECT * FROM `' . $resource->getTableName('catalog_product_entity_group_price') . '` WHERE entity_id = ' . $product_id;
            $rs = $read->fetchAll($select);
            foreach ($rs as $row) {
                $p_group_price[] = array(
                    'price_id' => $row['value_id'],
                    'website_id' => $row['website_id'],
                    'all_groups' => $row['all_groups'],
                    'cust_group' => $row['customer_group_id'],
                    'price' => $row['value']
                );
            }
        }
        if ($groups != null && is_array($groups)) {
            for ($i = 0; $i < count($p_group_price); $i++) {
                for ($j = 0; $j < count($groups); $j++) {
                    if (isset($groups[$j]['price_id']) && $groups[$j]['price_id'] != '') {
                        continue;
                    }
                    if ($groups[$j]['website_id'] == $p_group_price[$i]['website_id'] &&
                            $groups[$j]['all_groups'] == $p_group_price[$i]['all_groups'] &&
                            $groups[$j]['cust_group'] == $p_group_price[$i]['cust_group']) {
                        $groups[$j]['price_id'] = $p_group_price[$i]['price_id'];
                        $p_group_price[$i]['price'] = $groups[$j]['price'];
                        $p_group_price[$i]['website_price'] = $groups[$j]['price'];
                        $p_group_price[$i]['delete'] = '0';
                        break;
                    }
                }
            }
            $i = 0;
            for (; $i < count($p_group_price); $i++) {
                if (isset($p_group_price[$i]['delete']) && $p_group_price[$i]['delete'] == '0') {
                    continue;
                }
                $flg = false;
                for ($j = 0; $j < count($groups); $j++) {
                    if (!$flg) {
                        if (isset($groups[$j]['price_id']) && $groups[$j]['price_id'] != '') {
                            continue;
                        }

                        $flg = true;
                        foreach ($groups[$j] as $k => $v) {
                            $p_group_price[$i][$k] = $v;
                        }
                        $p_group_price[$i]['website_price'] = $groups[$j]['price'];
                        $groups[$j]['price_id'] = $p_group_price[$i]['price_id'];
                    }
                }
                if ($flg) {
                    $p_group_price[$i]['delete'] = '0';
                } else {
                    $p_group_price[$i]['delete'] = '1';
                }
            }
            for ($j = 0; $j < count($groups); $j++) {
                if (isset($groups[$j]['price_id']) && $groups[$j]['price_id'] != '') {
                    continue;
                }
                $p_group_price[$i] = array();
                foreach ($groups[$j] as $k => $v) {
                    $p_group_price[$i][$k] = $v;
                }
                $p_group_price[$i]['delete'] = '0';
                $i++;
            }
        }

        if ($product_id != null && (int) $product_id > 0) {
            $resource = Mage::getSingleton('core/resource');
            $write = $resource->getConnection('core_write');

            foreach ($p_group_price as $group) {
                if (isset($group['price_id']) && (int) $group['price_id'] > 0) {
                    if ($group['delete'] == '1') {
                        $sql = "DELETE FROM `" . $resource->getTableName('catalog_product_entity_group_price')
                                . "` WHERE `value_id` = :value_id";
                        $binds = array(
                            'value_id' => $group['price_id']
                        );
                        $write->query($sql, $binds);
                    } else {
                        $sql = "UPDATE `" . $resource->getTableName('catalog_product_entity_group_price')
                                . "` SET `entity_id` = :entity_id, `all_groups` = :all_groups, `customer_group_id` = :customer_group_id, `value` = :value, `website_id` = :website_id WHERE `value_id` = :value_id";
                        $binds = array(
                            'entity_id' => $product_id,
                            'all_groups' => $group['all_groups'],
                            'customer_group_id' => $group['cust_group'],
                            'value' => $group['price'],
                            'website_id' => $group['website_id'],
                            'value_id' => $group['price_id']
                        );
                        $write->query($sql, $binds);
                    }
                } else {
                    $sql = "INSERT INTO `" . $resource->getTableName('catalog_product_entity_group_price')
                            . "` SET `entity_id` = :entity_id, `all_groups` = :all_groups, `customer_group_id` = :customer_group_id, `value` = :value, `website_id` = :website_id";
                    $binds = array(
                        'entity_id' => $product_id,
                        'all_groups' => $group['all_groups'],
                        'customer_group_id' => $group['cust_group'],
                        'value' => $group['price'],
                        'website_id' => $group['website_id']
                    );
                    $write->query($sql, $binds);
                }
            }
        }
        return $p_group_price;
    }

    public function remoteProducts($vtigerId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $product = $data['crm4ecommerce'];
        $product_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_PRODUCT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_INFO);
        $productData = array();
        $name = '';
        $tax_class = 0;
        $visibility = 0;
        $f_tax_class = false;
        $f_tier_price = null;
        $f_group_price = null;

        foreach ($product_info_mapping as $field) {
            switch ($field->getAttributeCode()) {
                case 'name':
                    $name = $field->getVtigerColumn();
                    break;
                case 'tax_class_id':
                    $f_tax_class = true;
                    $tax_class = $field->getVtigerColumn();
                case 'visibility':
                    $visibility = $field->getVtigerColumn();
                    break;
                case 'tier_price':
                    $f_tier_price = $field->getVtigerColumn();
                    break;
                case 'group_price':
                    $f_group_price = $field->getVtigerColumn();
                    break;
            }
            if ($field->getAttributeCode() == 'name' ||
                    $field->getAttributeCode() == 'tax_class_id' ||
                    $field->getAttributeCode() == 'visibility' ||
                    $field->getAttributeCode() == 'tier_price' ||
                    $field->getAttributeCode() == 'group_price' ||
                    $field->getAttributeCode() == 'vtiger_id') {
                continue;
            }
            $productData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $product_stock_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_PRODUCT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_STOCK);
        $stockData = array();
        foreach ($product_stock_mapping as $field) {
            $stockData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $product_other_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_PRODUCT, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_OTHER);
        $vtiger_attribute_set_field = '';
        $vtiger_product_type_field = '';
        $vtiger_category_field = '';
        $vtiger_website_field = '';

        foreach ($product_other_mapping as $field) {
            switch ($field->getAttributeCode()) {
                case 'attribute_set':
                    $vtiger_attribute_set_field = $field->getVtigerColumn();
                    break;
                case 'product_type':
                    $vtiger_product_type_field = $field->getVtigerColumn();
                    break;
                case 'category':
                    $vtiger_category_field = $field->getVtigerColumn();
                    break;
                case 'websites':
                    $vtiger_website_field = $field->getVtigerColumn();
                    break;
            }
        }

        $product_data = array();
        $stock_data = array();
        $attribute_set = '';
        $product_type = '';
        $category = '';
        $website = null;
        $tax_class_v = 0;
        $tier_price = null;
        $group_price = null;
        $product_id = 0;

        foreach ($product as $key => $value) {
            $value = ($value == '' || (string) $value == '0' || (string) $value == '0000-00-00') ? null : $value;
            if ($name == $key) {
                $name = $value;
                $product_name_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/product_name');
                if ($product_name_format == '') {
                    $product_name_format = '{{productname}} (#{{product_id}})';
                }

                $parts = explode('{{productname}}', $product_name_format);
                $l_parts = explode('{{product_id}}', $parts[0]);
                $r_parts = explode('{{product_id}}', $parts[1]);

                if (count($l_parts) > 1) {
                    $name = str_replace('!@#$%^' . $l_parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($parts[1] . '!@#$%^', '', $name . '!@#$%^');
                    $_r = explode($l_parts[1], $name);
                    $_id = $_r[0];
                    $name = str_replace('!@#$%^' . $_id . $l_parts[1], '', '!@#$%^' . $name);
                } else if (count($r_parts) > 1) {
                    $name = str_replace('!@#$%^' . $parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($r_parts[1] . '!@#$%^', '', $name . '!@#$%^');
                    $_r = explode($r_parts[0], $name);
                    $_id = $_r[count($_r) - 1];
                    $name = str_replace($r_parts[0] . $_id . '!@#$%^', '', $name . '!@#$%^');
                } else {
                    $name = str_replace('!@#$%^' . $parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($parts[1] . '!@#$%^', '', $name . '!@#$%^');
                }
                $name = trim($name, '!@#$%^');
                continue;
            }
            if ($tax_class == $key) {
                if ($value != '') {
                    $tax_class_v = $value;
                }
                continue;
            }
            if ($key == 'remote_id') {
                $product_id = $value;
                continue;
            }
            if ($visibility == $key) {
                $product_data['visibility'] = $this->searchProductVisibilityLabel($value);
                continue;
            }
            if ($f_tier_price == $key) {
                $tier_price = $value;
                continue;
            }
            if ($f_group_price == $key) {
                $group_price = $value;
                continue;
            }
            if (key_exists($key, $productData) && $productData[$key] != '') {
                $_value = $this->searchAttribute($productData[$key], $value);
                if (!is_null($_value)) {
                    $value = $_value;
                }
                $product_data[$productData[$key]] = $productData[$key] == 'status' && $value == null ? 2 : $value;
            } else if (key_exists($key, $stockData) && $stockData[$key] != '') {
                $stock_data[$stockData[$key]] = $value;
            }
            switch ($key) {
                case $vtiger_attribute_set_field:
                    $attribute_set = $value;
                    break;
                case $vtiger_product_type_field:
                    $product_type = $value;
                    break;
                case $vtiger_category_field:
                    $category = $value;
                    break;
                case $vtiger_website_field:
                    $website = $value;
                    break;
            }
        }

        if (isset($stock_data['is_in_stock']) && $stock_data['is_in_stock'] != '') {
            $source_stock = Mage::getModel('cataloginventory/source_stock')->toOptionArray();
            foreach ($source_stock as $item) {
                if ($stock_data['is_in_stock'] == $item['label']) {
                    $stock_data['is_in_stock'] = $item['value'];
                    break;
                }
            }
        }
        if (isset($stock_data['backorders']) && $stock_data['backorders'] != '') {
            $source_backorders = Mage::getModel('cataloginventory/source_backorders')->toOptionArray();
            foreach ($source_backorders as $item) {
                if ($stock_data['backorders'] == $item['label']) {
                    $stock_data['backorders'] = $item['value'];
                    break;
                }
            }
        }

        if ($tax_class != '') {
            if ($tax_class_v != '') {
                $tax_classes = explode('| ## |', $tax_class_v);
                $_tax_class = 0;
                foreach ($tax_classes as $tax) {
                    $_tax_class = Mage::getModel('tax/class')->getCollection()
                            ->addFieldToFilter('class_name', array('eq' => $tax))
                            ->getFirstItem();
                    if ($_tax_class->getId() > 0) {
                        break;
                    }
                }
                if (!$_tax_class || !$_tax_class->getId()) {
                    return ' - ' . Mage::helper('vtigersynchronization')->__('Please check product tax. Tax(es) "%s" does not exists.', implode($tax_classes, ';')) . '<br/>';
                } else {
                    $tax_class = $_tax_class->getId();
                }
            } else {
                $tax_class = 0;
            }
        }

        $_product_type = Mage::getModel('vtigersynchronization/array_getListProductTypes')->getValue($product_type);
        $_attribute_set = Mage::getModel('vtigersynchronization/array_getListAttributeSets')->getValue($attribute_set);

        $categories = explode(' |##| ', $category);
        $category_ids = array();
        foreach ($categories as $category) {
            if ($category == '') {
                continue;
            }
            $_category = Mage::getModel("catalog/category")->getCollection()
                    ->addFieldToFilter('name', array('eq' => $category))
                    ->getFirstItem();
            if (!$_category || !$_category->getId()) {
                return ' - ' . Mage::helper('vtigersynchronization')->__('Please check product category. Category "%s" does not exists.', $category) . '<br/>';
            }
            $category_ids[] = $_category->getId();
        }
        $website_ids = null;
        if ($website != null) {
            $websites = explode(' |##| ', $website);
            $website_ids = array();
            foreach ($websites as $website) {
                if ($website == '') {
                    continue;
                }
                $_website = Mage::getModel("core/website")->getCollection()
                        ->addFieldToFilter('name', array('eq' => $website))
                        ->getFirstItem();
                if (!$_website || !$_website->getId()) {
                    return ' - ' . Mage::helper('vtigersynchronization')->__('Please check website name. Website "%s" does not exists.', $website) . '<br/>';
                }
                $website_ids[] = $_website->getId();
            }
        }

        $product_data['name'] = $name;
        $product_data['vtiger_id'] = $vtigerId;
        $product = Mage::getModel('catalog/product')->setStoreId(0)->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$product->getId() && (int) $product_id > 0) {
            $product = Mage::getModel('catalog/product')->setStoreId(0)->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $product_id))
                    ->getFirstItem();
        }

        if ($product->getId() > 0) {
            if ($tier_price != null) {
                $this->prepareTierPrice($tier_price, $product->getId());
            }
            if ($group_price != null) {
                $this->prepareGroupPrice($group_price, $product->getId());
            }
            $product = Mage::getModel('catalog/product')->setStoreId(0)->load($product->getId());
            $product->addData($product_data);

            if ($_product_type != null && $_product_type != '') {
                $product->setTypeId($_product_type);
            }
            if ($_attribute_set != null && $_attribute_set != '') {
                $product->setAttributeSetId($_attribute_set);
            }
            if ($f_tax_class) {
                $product->setTaxClassId($tax_class);
            }
            $product->setCategoryIds($category_ids);
            if ($website_ids != null) {
                $product->setWebsiteIds($website_ids);
            }

            $product->setStockData($stock_data);
            $tier_price = $product->getData('tier_price');
            for ($i = 0; $i < count($tier_price); $i++) {
                $tier_price[$i]['customer_group_id'] = $tier_price[$i]['cust_group'];
                unset($tier_price[$i]['cust_group']);
                $tier_price[$i]['value'] = $tier_price[$i]['price'];
                unset($tier_price[$i]['price']);
                unset($tier_price[$i]['website_price']);
            }
            if ($tier_price != null) {
                $product->setData('tier_price', $tier_price);
                $product->setData('tier_price_changed', 1);
            }
            $group_price = $product->getData('group_price');
            for ($i = 0; $i < count($group_price); $i++) {
                $group_price[$i]['customer_group_id'] = $group_price[$i]['cust_group'];
                unset($group_price[$i]['cust_group']);
                $group_price[$i]['value'] = $group_price[$i]['price'];
                unset($group_price[$i]['price']);
                unset($group_price[$i]['website_price']);
            }
            if ($group_price != null) {
                $product->setData('group_price', $group_price);
                $product->setData('group_price_changed', 1);
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::PRODUCT)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($product->getId())
                    ->setToId($product->getId())
                    ->setNumberSuccess(1)->setSuccessIds($product->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($product->getId(), $product->getName())->save();
            Mage::getModel('core/session')->setData('remote', true);
            $product->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Product "%s" (Id %s) have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId())), $product->getName()
                                ), $product->getId()
                        ) . '<br/>';
            } else {
                return $product->getId();
            }
        } else {
            $product = Mage::getModel('catalog/product');
            $product->addData($product_data);

            if ($_product_type == '' || $_product_type == null) {
                $_product_type = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/default_product_type');
            }
            $product->setTypeId($_product_type);

            if ($_attribute_set == '' || $_attribute_set == null) {
                $_attribute_set = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/default_attribute_set');
            }
            $product->setAttributeSetId($_attribute_set);
            $product->setCategoryIds($category_ids);
            if ($website_ids != null) {
                $product->setWebsiteIds($website_ids);
            }
            if ($f_tax_class) {
                $product->setTaxClassId($tax_class);
            }

            if ($tier_price != null) {
                $product->setData('tier_price', $this->prepareTierPrice($tier_price));
            }
            if ($group_price != null) {
                $product->setData('group_price', $this->prepareGroupPrice($group_price));
            }

            $product->setStockData($stock_data);

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::PRODUCT)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($product->getId())
                    ->setToId($product->getId())
                    ->setNumberSuccess(1)->setSuccessIds($product->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($product->getId(), $product->getName())->save();
            Mage::getModel('core/session')->setData('remote', true);
            $product->save();
            Mage::getModel('core/session')->setData('remote', false);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('A new product has id %s have been created successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId())), $product->getName()
                                ), $product->getId()
                        ) . '<br/>';
            } else {
                return $product->getId();
            }
        }
    }

    public function remoteServices($vtigerId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $product = $data['crm4ecommerce'];
        $product_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_SERVICE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_INFO);
        $productData = array();
        $name = '';
        $tax_class = 0;
        $visibility = 0;
        $f_tax_class = false;
        $f_tier_price = null;
        $f_group_price = null;

        foreach ($product_info_mapping as $field) {
            switch ($field->getAttributeCode()) {
                case 'name':
                    $name = $field->getVtigerColumn();
                    break;
                case 'tax_class_id':
                    $f_tax_class = true;
                    $tax_class = $field->getVtigerColumn();
                    break;
                case 'visibility':
                    $visibility = $field->getVtigerColumn();
                    break;
                case 'tier_price':
                    $f_tier_price = $field->getVtigerColumn();
                    break;
                case 'group_price':
                    $f_group_price = $field->getVtigerColumn();
                    break;
            }
            if ($field->getAttributeCode() == 'name' ||
                    $field->getAttributeCode() == 'tax_class_id' ||
                    $field->getAttributeCode() == 'visibility' ||
                    $field->getAttributeCode() == 'tier_price' ||
                    $field->getAttributeCode() == 'group_price' ||
                    $field->getAttributeCode() == 'vtiger_id') {
                continue;
            }
            $productData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $product_stock_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_SERVICE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_STOCK);
        $stockData = array();
        foreach ($product_stock_mapping as $field) {
            $stockData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $product_other_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_SERVICE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::PRODUCT_OTHER);
        $vtiger_attribute_set_field = '';
        $vtiger_product_type_field = '';
        $vtiger_category_field = '';
        $vtiger_website_field = '';

        foreach ($product_other_mapping as $field) {
            switch ($field->getAttributeCode()) {
                case 'attribute_set':
                    $vtiger_attribute_set_field = $field->getVtigerColumn();
                    break;
                case 'product_type':
                    $vtiger_product_type_field = $field->getVtigerColumn();
                    break;
                case 'category':
                    $vtiger_category_field = $field->getVtigerColumn();
                    break;
                case 'websites':
                    $vtiger_website_field = $field->getVtigerColumn();
                    break;
            }
        }

        $product_data = array();
        $attribute_set = '';
        $product_type = '';
        $category = '';
        $website = '';
        $tax_class_v = 0;
        $tier_price = null;
        $group_price = null;
        $product_id = 0;
        $stock_data = array();

        foreach ($product as $key => $value) {
            $value = ($value == '' || (string) $value == '0') ? null : $value;
            if ($name == $key) {
                $name = $value;
                $product_name_format = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/service_name');
                if ($product_name_format == '') {
                    $product_name_format = '{{productname}} (#{{product_id}})';
                }

                $parts = explode('{{productname}}', $product_name_format);
                $l_parts = explode('{{product_id}}', $parts[0]);
                $r_parts = explode('{{product_id}}', $parts[1]);

                if (count($l_parts) > 1) {
                    $name = str_replace('!@#$%^' . $l_parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($parts[1] . '!@#$%^', '', $name . '!@#$%^');
                    $_r = explode($l_parts[1], $name);
                    $_id = $_r[0];
                    $name = str_replace('!@#$%^' . $_id . $l_parts[1], '', '!@#$%^' . $name);
                } else if (count($r_parts) > 1) {
                    $name = str_replace('!@#$%^' . $parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($r_parts[1] . '!@#$%^', '', $name . '!@#$%^');
                    $_r = explode($r_parts[0], $name);
                    $_id = $_r[count($_r) - 1];
                    $name = str_replace($r_parts[0] . $_id . '!@#$%^', '', $name . '!@#$%^');
                } else {
                    $name = str_replace('!@#$%^' . $parts[0], '', '!@#$%^' . $name);
                    $name = str_replace($parts[1] . '!@#$%^', '', $name . '!@#$%^');
                }
                $name = trim($name, '!@#$%^');
                continue;
            }
            if ($key == 'remote_id') {
                $product_id = $value;
                continue;
            }
            if ($tax_class == $key) {
                if ($value != '') {
                    $tax_class_v = $value;
                }
                continue;
            }
            if ($visibility == $key) {
                $product_data['visibility'] = $this->searchProductVisibilityLabel($value);
                continue;
            }
            if ($f_tier_price == $key) {
                $tier_price = $value;
                continue;
            }
            if ($f_group_price == $key) {
                $group_price = $value;
                continue;
            }
            if (key_exists($key, $productData) && $productData[$key] != '') {
                $_value = $this->searchAttribute($productData[$key], $value);
                if (!is_null($_value)) {
                    $value = $_value;
                }
                $product_data[$productData[$key]] = $productData[$key] == 'status' && $value == null ? 2 : $value;
            } else if (key_exists($key, $stockData) && $stockData[$key] != '') {
                $stock_data[$stockData[$key]] = $value;
            }
            switch ($key) {
                case $vtiger_attribute_set_field:
                    $attribute_set = $value;
                    break;
                case $vtiger_product_type_field:
                    $product_type = $value;
                    break;
                case $vtiger_category_field:
                    $category = $value;
                    break;
                case $vtiger_website_field:
                    $website = $value;
                    break;
            }
        }

        if (isset($stock_data['is_in_stock']) && $stock_data['is_in_stock'] != '') {
            $source_stock = Mage::getModel('cataloginventory/source_stock')->toOptionArray();
            foreach ($source_stock as $item) {
                if ($stock_data['is_in_stock'] == $item['label']) {
                    $stock_data['is_in_stock'] = $item['value'];
                    break;
                }
            }
        }
        if (isset($stock_data['backorders']) && $stock_data['backorders'] != '') {
            $source_backorders = Mage::getModel('cataloginventory/source_backorders')->toOptionArray();
            foreach ($source_backorders as $item) {
                if ($stock_data['backorders'] == $item['label']) {
                    $stock_data['backorders'] = $item['value'];
                    break;
                }
            }
        }

        if ($tax_class != '') {
            if ($tax_class_v != '') {
                $tax_classes = explode('| ## |', $tax_class_v);
                $_tax_class = 0;
                foreach ($tax_classes as $tax) {
                    $_tax_class = Mage::getModel('tax/class')->getCollection()
                            ->addFieldToFilter('class_name', array('eq' => $tax))
                            ->getFirstItem();
                    if ($_tax_class->getId() > 0) {
                        break;
                    }
                }
                if (!$_tax_class || !$_tax_class->getId()) {
                    return ' - ' . Mage::helper('vtigersynchronization')->__('Please check product tax. Tax(es) "%s" does not exists.', implode($tax_classes, ';')) . '<br/>';
                } else {
                    $tax_class = $_tax_class->getId();
                }
            } else {
                $tax_class = 0;
            }
        }

        $_product_type = Mage::getModel('vtigersynchronization/array_getListProductTypes')->getValue($product_type);
        if ($_product_type == '') {
            $_product_type = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/service_default_product_type');
        }

        $_attribute_set = Mage::getModel('vtigersynchronization/array_getListAttributeSets')->getValue($attribute_set);
        if ($_attribute_set == '') {
            $_attribute_set = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/service_default_attribute_set');
        }
        $categories = explode(' |##| ', $category);
        $category_ids = array();
        foreach ($categories as $category) {
            if ($category == '') {
                continue;
            }
            $_category = Mage::getModel("catalog/category")->getCollection()
                    ->addFieldToFilter('name', array('eq' => $category))
                    ->getFirstItem();
            if (!$_category || !$_category->getId()) {
                return ' - ' . Mage::helper('vtigersynchronization')->__('Please check product category. Category "%s" does not exists.', $category) . '<br/>';
            }
            $category_ids[] = $_category->getId();
        }

        $website_ids = null;
        if ($website != null) {
            $websites = explode(' |##| ', $website);
            $website_ids = array();
            foreach ($websites as $website) {
                if ($website == '') {
                    continue;
                }
                $_website = Mage::getModel("core/website")->getCollection()
                        ->addFieldToFilter('name', array('eq' => $website))
                        ->getFirstItem();
                if (!$_website || !$_website->getId()) {
                    return ' - ' . Mage::helper('vtigersynchronization')->__('Please check website name. Website "%s" does not exists.', $website) . '<br/>';
                }
                $website_ids[] = $_website->getId();
            }
        }

        $product_data['vtiger_id'] = $vtigerId;
        $product_data['name'] = $name;
        $product = Mage::getModel('catalog/product')->setStoreId(0)->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$product->getId() && (int) $product_id > 0) {
            $product = Mage::getModel('catalog/product')->setStoreId(0)->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $product_id))
                    ->getFirstItem();
        }

        if ($product->getId() > 0) {
            if ($tier_price != null) {
                $this->prepareTierPrice($tier_price, $product->getId());
            }
            if ($group_price != null) {
                $this->prepareGroupPrice($group_price, $product->getId());
            }
            $product = Mage::getModel('catalog/product')->setStoreId(0)->load($product->getId());
            $product->addData($product_data);

            $product->setTypeId($_product_type);
            $product->setAttributeSetId($_attribute_set);
            if ($f_tax_class) {
                $product->setTaxClassId($tax_class);
            }
            $product->setCategoryIds($category_ids);
            if ($website_ids != null) {
                $product->setWebsiteIds($website_ids);
            }

            $product->setStockData($stock_data);
            $tier_price = $product->getData('tier_price');
            for ($i = 0; $i < count($tier_price); $i++) {
                $tier_price[$i]['customer_group_id'] = $tier_price[$i]['cust_group'];
                unset($tier_price[$i]['cust_group']);
                $tier_price[$i]['value'] = $tier_price[$i]['price'];
                unset($tier_price[$i]['price']);
                unset($tier_price[$i]['website_price']);
            }
            if ($tier_price != null) {
                $product->setData('tier_price', $tier_price);
                $product->setData('tier_price_changed', 1);
            }
            $group_price = $product->getData('group_price');
            for ($i = 0; $i < count($group_price); $i++) {
                $group_price[$i]['customer_group_id'] = $group_price[$i]['cust_group'];
                unset($group_price[$i]['cust_group']);
                $group_price[$i]['value'] = $group_price[$i]['price'];
                unset($group_price[$i]['price']);
                unset($group_price[$i]['website_price']);
            }
            if ($group_price != null) {
                $product->setData('group_price', $group_price);
                $product->setData('group_price_changed', 1);
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::PRODUCT)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($product->getId())
                    ->setToId($product->getId())
                    ->setNumberSuccess(1)->setSuccessIds($product->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($product->getId(), $product->getName())->save();
            $product->save();

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Product "%s" (Id %s) have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId())), $product->getName()
                                ), $product->getId()
                        ) . '<br/>';
            } else {
                return $product->getId();
            }
        } else {
            $product = Mage::getModel('catalog/product');
            $product->addData($product_data);

            $product->setTypeId($_product_type);
            $product->setAttributeSetId($_attribute_set);
            $product->setCategoryIds($category_ids);
            $product->setWebsiteIds($website_ids);
            $product->setVtigerType(Mage::helper('vtigersynchronization')->__('Services'));
            if ($f_tax_class) {
                $product->setTaxClassId($tax_class);
            }

            if ($tier_price != null) {
                $product->setData('tier_price', $this->prepareTierPrice($tier_price));
            }
            if ($group_price != null) {
                $product->setData('group_price', $this->prepareGroupPrice($group_price));
            }

            $product->setStockData($stock_data);

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::PRODUCT)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($product->getId())
                    ->setToId($product->getId())
                    ->setNumberSuccess(1)->setSuccessIds($product->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($product->getId(), $product->getName())->save();
            $product->save();

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('A new product has id %s have been created successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId())), $product->getName()
                                ), $product->getId()
                        ) . '<br/>';
            } else {
                return $product->getId();
            }
        }
    }

    public function getSalerule(&$coupon_codes) {
        if ($coupon_codes != '') {
            $coupon_codes = explode(' |##| ', $coupon_codes);
            $rule_collection = Mage::getModel('salesrule/rule')->getCollection();
            $rule_ids = '';
            foreach ($rule_collection as $rule) {
                foreach ($coupon_codes as $code) {
                    if ($rule->getCode() == $code) {
                        $rule_ids .= $rule->getId() . ',';
                        break;
                    }
                }
            }
            $coupon_codes = implode($coupon_codes, ', ');
            return rtrim($rule_ids, ',');
        } else {
            return '';
        }
    }

    public function remoteQuotes($vtigerId, $storeId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }
        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));

        $quote = $data['crm4ecommerce'];
        $quote_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_QUOTE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::QUOTE_INFO);
        $quoteData = array();
        foreach ($quote_info_mapping as $field) {
            $quoteData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $quote_billing_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_QUOTE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::QUOTE_BILL);
        $quoteBillData = array();
        foreach ($quote_billing_mapping as $field) {
            $quoteBillData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $quote_shipping_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_QUOTE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::QUOTE_SHIP);
        $quoteShipData = array();
        foreach ($quote_shipping_mapping as $field) {
            $quoteShipData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $quote_data = array();
        $quote_bill_data = array();
        $quote_ship_data = array();
        $product_nodes = null;
        $customer = null;
        $disable_quote = false;
        $conversion_rate = isset($quote['conversion_rate']) ? floatval($quote['conversion_rate']) : 1;
        Mage::getModel('core/session')->setQuoteCurrencyRate($conversion_rate);
        $quote_id = 0;
        $discount_percent = 0;

        $store_name = '';
        $store_group_name = '';
        $website_name = '';

        foreach ($quote as $key => $value) {
            if ($key == 'remote_id') {
                $quote_id = $value;
                continue;
            }
            switch ($key) {
                case 'quotestage':
                    if ($value == Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_stage_closed_lost')) {
                        $disable_quote = true;
                    }
                    break;
                case 'items':
                    $product_nodes = $value;
                    break;
                case 'account_id':
                    $customer = Mage::getModel('customer/customer')->getCollection()
                            ->addFieldToFilter('vtiger_id', array('eq' => $value))
                            ->getFirstItem();
                    if ($customer->getId() > 0) {
                        $quote_data['customer_id'] = $customer->getId();
                    }
                    break;
                case 'currency_id':
                    $currency = Mage::getModel('vtigersynchronization/mapping_currency')->getCurrencyByVtigerId($value);
                    if (is_null($currency)) {
                        return ' - ' . Mage::helper('vtigersynchronization')->__('Please check mapping between your store currency and currency of this Vtiger quote.') . '<br/>';
                    }
                    Mage::app()->getStore()->setCurrentCurrencyCode($currency->getCurrencyCode());
                    Mage::getModel('core/session')->setQuoteCurrencyCode($currency->getCurrencyCode());
                    break;
                case 'conversion_rate':
                    continue;
                case 'hdnSubTotal':
                    $quote_data['subtotal'] = floatval($value);
                    $quote_data['base_subtotal'] = floatval($value) / $conversion_rate;
                    $quote_ship_data['subtotal'] = $quote_data['subtotal'];
                    $quote_ship_data['base_subtotal'] = $quote_data['base_subtotal'];
                    break;
                case 'hdnDiscountPercent':
                    $discount_percent = floatval($value);
                    break;
                case 'hdnDiscountAmount':
                    $quote_ship_data['discount_amount'] = floatval($value);
                    $quote_ship_data['base_discount_amount'] = floatval($value) / $conversion_rate;
                    break;
                case 'hdnS_H_Amount':
                    $quote_ship_data['shipping_amount'] = floatval($value);
                    $quote_ship_data['base_shipping_amount'] = floatval($value) / $conversion_rate;
                    break;
                case 'tax_amount':
                    $quote_ship_data['tax_amount'] = floatval($value);
                    $quote_ship_data['base_tax_amount'] = floatval($value) / $conversion_rate;
                    break;
                case 'hdnGrandTotal':
                    $quote_data['grand_total'] = floatval($value);
                    $quote_data['base_grand_total'] = floatval($value) / $conversion_rate;
                    $quote_ship_data['grand_total'] = $quote_data['grand_total'];
                    $quote_ship_data['base_grand_total'] = $quote_data['base_grand_total'];
                    break;
                default :
                    if (key_exists($key, $quoteData) && $quoteData[$key] != '') {
                        switch ($quoteData[$key]) {
                            case 'coupon_code':
                                $rule_ids = $this->getSalerule($value);
                                $quote_data['applied_rule_ids'] = $rule_ids;
                                $quote_data[$quoteData[$key]] = $value;
                                $quote_ship_data['discount_description'] = $value;
                                break;
                            case 'currency_code':
                                continue;
                            case 'website_id':
                                $website_name = $value;
                                break;
                            case 'store_group_id':
                                $store_group_name = $value;
                                break;
                            case 'store_id':
                                $store_name = $value;
                                break;
                            default :
                                $quote_data[$quoteData[$key]] = $value;
                        }
                    }
                    if (key_exists($key, $quoteBillData) && $quoteBillData[$key] != '') {
                        if ($quoteBillData[$key] == 'country_id') {
                            $quote_bill_data['country_id'] = $this->searchCountry($value);
                        } else {
                            $quote_bill_data[$quoteBillData[$key]] = $value;
                        }
                    }
                    if (key_exists($key, $quoteShipData) && $quoteShipData[$key] != '') {
                        if ($quoteShipData[$key] == 'country_id') {
                            $quote_ship_data['country_id'] = $this->searchCountry($value);
                        } else if ($quoteShipData[$key] == 'shipping_method') {
                            $quote_ship_data['shipping_description'] = $value;
                            $quote_ship_data['shipping_method'] = $this->searchShippingMethod($value);
                        } else {
                            $quote_ship_data[$quoteShipData[$key]] = $value;
                        }
                    }
            }
        }

        if (floatval($discount_percent) == 0 && floatval($quote_ship_data['discount_amount']) > 0) {
            $discount_percent = floatval($quote_data['discount_amount']) / floatval($quote_data['subtotal']) * 100;
        } else if (floatval($quote_ship_data['discount_amount']) == 0 && floatval($discount_percent) > 0) {
            $quote_ship_data['discount_amount'] = floatval($quote_data['subtotal']) * floatval($discount_percent) / 100;
            $quote_ship_data['base_discount_amount'] = floatval($quote_ship_data['discount_amount']) / $conversion_rate;
        }

        $quote_data['subtotal_with_discount'] = floatval($quote_data['subtotal']) - floatval($quote_ship_data['discount_amount']);
        $quote_data['base_subtotal_with_discount'] = floatval($quote_data['base_subtotal']) - floatval($quote_ship_data['base_discount_amount']);
        $quote_ship_data['subtotal_with_discount'] = $quote_data['subtotal_with_discount'];
        $quote_ship_data['base_subtotal_with_discount'] = $quote_data['base_subtotal_with_discount'];

        $quote_data['vtiger_id'] = $vtigerId;
        $quote = Mage::getModel('sales/quote')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$quote->getId() && (int) $quote_id > 0) {
            $quote = Mage::getModel('sales/quote')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $quote_id))
                    ->getFirstItem();
        }

        $addNewFlag = false;
        $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name, $storeId);
        $storeIds = explode(',', $storeId);
        $storeId = $storeIds[2];

        if (is_null($quote->getId())) {
            $addNewFlag = true;

            $old_quote_collection = Mage::getModel('sales/quote')->getCollection()
                    ->addFieldToFilter('customer_id', array('eq' => $customer->getId()))
                    ->addFieldToFilter('is_active', array('eq' => 1));
            foreach ($old_quote_collection as $old_quote) {
                $old_quote->setIsActive(0)->save();
            }

            $quote = Mage::getModel('sales/quote');
            $quote->setStoreId($storeId);
            $quote->setCustomerId($customer->getId());
            $quote->setCustomerEmail($customer->getEmail());
            $quote->addData($quote_data)->setIsActive(true)->save();
        } else if (intval($storeId) > 0 && $storeId != $quote->getStoreId()) {
            $quote->setStoreId($storeId);
        }

        if (!is_null($product_nodes)) {
            $items = $quote->getAllItems();
            $product_ids = array();
            if (count($items) > 0) {
                foreach ($items as $item) {
                    $product_ids[$item->getProductId()] = array(
                        $item,
                        false
                    );
                }
            }

            $quote_items_count = 0;
            $quote_items_qty = 0;
            foreach ($product_nodes as $k_node => $product_node) {
                $quote_items_count++;
                $vtiger_quote_item = array();
                $product = null;
                foreach ($product_node as $k => $v) {
                    switch ($k) {
                        case 'productid':
                            $product = Mage::getModel('catalog/product')->getCollection()
                                    ->addFieldToFilter('vtiger_id', array('eq' => $v))
                                    ->getFirstItem();
                            $vtiger_quote_item['product_id'] = $product->getId();
                            break;
                        case 'listprice':
                            $vtiger_quote_item['base_price'] = floatval($v) / floatval($conversion_rate);
                            $vtiger_quote_item['vtiger_list_price'] = floatval($v) / floatval($conversion_rate);
                            break;
                        case 'listprice_after_discount':
                            $vtiger_quote_item['price'] = floatval($v) / floatval($conversion_rate);
                            $vtiger_quote_item['custom_price'] = floatval($v);
                            $vtiger_quote_item['original_custom_price'] = floatval($v);
                            break;
                        case 'quantity':
                            $quote_items_qty += (int) $v;
                            $vtiger_quote_item['qty'] = $v;
                            break;
                        case 'tax_amount':
                            $vtiger_quote_item['tax_amount'] = $v;
                            $vtiger_quote_item['base_tax_amount'] = floatval($v) / floatval($conversion_rate);
                            break;
                        case 'tax_percent':
                            $vtiger_quote_item['tax_percent'] = $v;
                            break;
                    }
                }
                $vtiger_quote_item['discount_percent'] = $discount_percent;
                $vtiger_quote_item['discount_amount'] = floatval($vtiger_quote_item['listprice_after_discount']) * floatval($vtiger_quote_item['qty']) * floatval($discount_percent);
                $vtiger_quote_item['base_discount_amount'] = floatval($vtiger_quote_item['discount_amount']) / floatval($conversion_rate);

                if (isset($product_ids[$vtiger_quote_item['product_id']])) {
                    $product_ids[$vtiger_quote_item['product_id']][1] = true;
                    $item = $product_ids[$vtiger_quote_item['product_id']][0];
                    $item->addData($vtiger_quote_item)->calcRowTotal()->calcTaxAmount()->save();
                    $parent_item = $item->getParentItem();
                    if (!is_null($parent_item) && $parent_item->getProductType() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
                        $vtiger_quote_item['product_id'] = $parent_item->getProductId();
                        $parent_item->addData($vtiger_quote_item)->calcRowTotal()->calcTaxAmount()->save();
                    }
                } else {
                    $product = Mage::getModel('catalog/product')->load($product->getId());
                    $parent_product = null;
                    $parent_item = null;
                    if ($product->getVisibility() == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE
                            && $product->getTypeId() == 'simple') {
                        $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
                        $parent_id = 0;
                        if (count($parentIds) > 0) {
                            foreach ($parentIds as $_parent_product_id) {
                                $_parent_product = Mage::getModel('catalog/product')->load($_parent_product_id);
                                if (str_replace("!@#$%^" . $_parent_product->getSku(), "", "!@#$%^" . $product->getSku()) != "!@#$%^" . $product->getSku()) {
                                    $parent_id = $_parent_product_id;
                                    $parent_product = $_parent_product;
                                    break;
                                } else if ($parent_id == 0) {
                                    $parent_id = $_parent_product_id;
                                    $parent_product = $_parent_product;
                                }
                            }

                            $_attributes = $parent_product->getTypeInstance(true)->getConfigurableAttributes($parent_product);
                            $attributes = array();
                            foreach ($_attributes as $_attribute) {
                                $attributes[$_attribute->getAttributeId()] = $product->getData($_attribute->getProductAttribute()->getAttributeCode());
                            }

                            $parent_item = Mage::getModel('sales/quote_item')->setQuote($quote);
                            $vtiger_quote_item['store_id'] = $quote->getStoreId();
                            $vtiger_quote_item['sku'] = $product->getSku();
                            $vtiger_quote_item['product_type'] = 'configurable';
                            $parent_item->setData($vtiger_quote_item)->setProduct($parent_product)
                                    ->addOption(new Varien_Object(
                                                    array(
                                                        'product' => $parent_item->getProduct(),
                                                        'code' => 'attributes',
                                                        'value' => serialize($attributes)
                                                    )
                                    ))->addOption(new Varien_Object(
                                            array(
                                                'product' => $product,
                                                'code' => 'product_qty_' . $product->getId(),
                                                'value' => $vtiger_quote_item['qty']
                                            )
                            ))->addOption(new Varien_Object(
                                            array(
                                                'product' => $product,
                                                'code' => 'simple_product',
                                                'value' => $product->getId()
                                            )
                            ))->calcRowTotal()->calcTaxAmount()->save();
                            $quote->addItem($parent_item);
                            $vtiger_quote_item['product_type'] = 'simple';
                        }
                    }

                    $item = Mage::getModel('sales/quote_item')->setQuote($quote)->setProduct($product);
                    $vtiger_quote_item['store_id'] = $quote->getStoreId();
                    $item->setData($vtiger_quote_item);
                    if (!is_null($parent_item)) {
                        $item->setParentItem($parent_item)
                                ->addOption(new Varien_Object(
                                                array(
                                                    'product' => $product,
                                                    'code' => 'parent_product_id',
                                                    'value' => $parent_product->getId()
                                                )
                                ));
                    }
                    $item->calcRowTotal()->calcTaxAmount()->save();
                    $quote->addItem($item);
                    Mage::getModel('core/session')->setQuoteCreatedNewItems(true);
                }
            }
            foreach ($items as $item) {
                $parent_item = $item->getParentItem();
                if (!is_null($parent_item)) {
                    if ($product_ids[$item->getProductId()][1]) {
                        $product_ids[$parent_item->getProductId()][1] = true;
                    } else {
                        if ($product_ids[$parent_item->getProductId()][1]) {
                            $product_ids[$item->getProductId()][1] = true;
                        }
                    }
                }
            }

            foreach ($product_ids as $id => $value) {
                if (!$value[1]) {
                    $quote->removeItem($value[0]->getId());
                    $value[0]->delete();
                }
            }
            $quote_data['items_count'] = $quote_items_count;
            $quote_data['items_qty'] = $quote_items_qty;
        }

        $billads = $quote->getBillingAddress();
        $billads->addData($quote_bill_data)->save();
        $shipads = $quote->getShippingAddress();
        if ($shipads) {
            $shipads->addData($quote_ship_data)->setCollectShippingRates(true)->save();
        }

        $quote->addData($quote_data);
        if ($disable_quote) {
            $quote->setIsActive(false);
        } else {
            $quote->setIsActive(true);
        }

        Mage::getModel('vtigersynchronization/log')
                ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::QUOTE)
                ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                ->setFromId($quote->getId())
                ->setToId($quote->getId())
                ->setNumberSuccess(1)->setSuccessIds($quote->getId())->setNumberFailure(0)
                ->setFailureIds('')->setStatus(true)->addLogSuccess($quote->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_subject_prefix') . $quote->getId())->save();
        $quote->collectTotals()->save();

        if (!$return_id) {
            if ($addNewFlag) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Quote Id "%s" have been created new successfully.', $quote->getId()) . '<br/>';
            } else {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Quote Id "%s" have been updated successfully.', $quote->getId()) . '<br/>';
            }
        } else {
            return $quote->getId();
        }
    }

    public function remoteOrders($vtigerId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }
        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $salesorder = $data['crm4ecommerce'];

        $order_info_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_ORDER, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ORDER_INFO);
        $orderData = array();
        foreach ($order_info_mapping as $field) {
            $orderData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $order_billing_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_ORDER, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ORDER_BILL);
        $orderBillData = array();
        foreach ($order_billing_mapping as $field) {
            $orderBillData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $order_shipping_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_ORDER, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ORDER_SHIP);
        $orderShipData = array();
        foreach ($order_shipping_mapping as $field) {
            $orderShipData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $order_data = array();
        $order_bill_data = array();
        $order_ship_data = array();
        $statuses = Mage::getSingleton('sales/order_config')->getStatuses();
        $status = '';
        $product_nodes = null;

        $shipping_amount = 0;
        $tax_amount = 0;
        $discount_amount = 0;
        $discount_percent = 0;
        $subtotal = 0;
        $grand_total = 0;
        $total_due = 0;
        $order_id = 0;
        $conversion_rate = isset($salesorder['conversion_rate']) ? floatval($salesorder['conversion_rate']) : 1;
        $currency = Mage::getModel('vtigersynchronization/mapping_currency')->getCurrencyByVtigerId($salesorder['currency_id']);
        if (is_null($currency)) {
            return ' - ' . Mage::helper('vtigersynchronization')->__('Please check mapping between your store currency and currency of this Vtiger salesorder.') . '<br/>';
        }
        $order_currency_code = $currency->getCurrencyCode();

        $store_name = '';
        $store_group_name = '';
        $website_name = '';

        foreach ($salesorder as $key => $value) {
            if ($key == 'remote_id') {
                $order_id = $value;
                continue;
            }
            switch ($key) {
                case 'sostatus':
                    foreach ($statuses as $status_key => $status_label) {
                        if ($status_label == $value) {
                            $status = $status_key;
                        }
                    }
                    break;
                case 'items':
                    $product_nodes = $value;
                    break;
                case 'hdnDiscountAmount':
                    $discount_amount = floatval($value);
                    break;
                case 'hdnDiscountPercent':
                    $discount_percent = floatval($value);
                    break;
                case 'hdnS_H_Amount':
                    $shipping_amount = floatval($value);
                    break;
                case 'currency_id':
                    continue;
                case 'conversion_rate':
                    continue;
                default :
                    if (key_exists($key, $orderData) && $orderData[$key] != '') {
                        switch ($orderData[$key]) {
                            case 'coupon_code':
                                $rule_ids = $this->getSalerule($value);
                                $order_data['applied_rule_ids'] = $rule_ids;
                                $order_data['discount_description'] = $value;
                                break;
                            case 'currency_code':
                                continue;
                            case 'website_id':
                                $website_name = $value;
                                break;
                            case 'store_group_id':
                                $store_group_name = $value;
                                break;
                            case 'store_id':
                                $store_name = $value;
                                break;
                            case 'customer_group_id':
                                $order_data['customer_group_id'] = $this->getCustomerGroupCode($value);
                                break;
                            case 'shipping_method':
                                $order_data['shipping_description'] = $value;
                                $order_data['shipping_method'] = $this->searchShippingMethod($value);
                                break;
                            case 'payment_method':
                                continue;
                            default :
                                $order_data[$orderData[$key]] = $value;
                        }
                    }
                    if (key_exists($key, $orderBillData) && $orderBillData[$key] != '') {
                        if ($orderBillData[$key] == 'country_id') {
                            $order_bill_data['country_id'] = $this->searchCountry($value);
                        } else {
                            $order_bill_data[$orderBillData[$key]] = $value;
                        }
                    }
                    if (key_exists($key, $orderShipData) && $orderShipData[$key] != '') {
                        if ($orderShipData[$key] == 'country_id') {
                            $order_ship_data['country_id'] = $this->searchCountry($value);
                        } else {
                            $order_ship_data[$orderShipData[$key]] = $value;
                        }
                    }
            }
        }

        $order = Mage::getModel('sales/order')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$order->getId() && (int) $order_id > 0) {
            $order = Mage::getModel('sales/order')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $order_id))
                    ->getFirstItem();
        }

        $storeId = $this->searchStoreId($website_name, $store_group_name, $store_name, $storeId);
        $storeIds = explode(',', $storeId);
        $storeId = $storeIds[2];

        if ($order->getId() > 0) {
            $order = Mage::getModel('sales/order')->loadByIncrementId($order->getIncrementId());
            if (intval($storeId) > 0 && $order->getStoreId() != $storeId) {
                $order->setStoreId($storeId);
            }
            $order->addData($order_data);

            $billads = $order->getBillingAddress();
            $billads->addData($order_bill_data)->save();
            $shipads = $order->getShippingAddress();
            if ($shipads) {
                $shipads->addData($order_ship_data)->save();
            }

            $products = array();
            if (!is_null($product_nodes)) {
                $items = $order->getAllItems();
                foreach ($items as $item) {
                    $products[$item->getProductId()] = array(
                        $item,
                        false
                    );
                }

                $total_item_count = 0;
                foreach ($product_nodes as $k_node => $product_node) {
                    $vtiger_order_item = array();
                    $product = null;
                    foreach ($product_node as $k => $v) {
                        switch ($k) {
                            case 'productid':
                                $product = Mage::getModel('catalog/product')->getCollection()
                                        ->addFieldToFilter('vtiger_id', array('eq' => $v))
                                        ->getFirstItem();
                                $product = Mage::getModel('catalog/product')
                                        ->setStoreId($order->getStoreId())
                                        ->load($product->getId());
                                $vtiger_order_item['product_id'] = $product->getId();
                                $vtiger_order_item['product_type'] = $product->getTypeId();
                                $vtiger_order_item['sku'] = $product->getSku();
                                $vtiger_order_item['name'] = $product->getName();
                                break;
                            case 'listprice_after_discount':
                                $vtiger_order_item['price'] = floatval($v);
                                $vtiger_order_item['base_price'] = floatval($v) / $conversion_rate;
                                break;
                            case 'listprice':
                                $vtiger_order_item['original_price'] = floatval($v);
                                $vtiger_order_item['base_original_price'] = floatval($v) / $conversion_rate;
                                break;
                            case 'quantity':
                                $vtiger_order_item['qty_ordered'] = $v;
                                $total_item_count += intval($v);
                                break;
                            case 'tax_percent':
                                $vtiger_order_item['tax_percent'] = floatval($v);
                                break;
                            case 'tax_amount':
                                $vtiger_order_item['tax_amount'] = floatval($v);
                                $vtiger_order_item['base_tax_amount'] = floatval($v) / $conversion_rate;
                                $tax_amount += floatval($v);
                                break;
                        }
                    }
                    $vtiger_order_item['discount_percent'] = $discount_percent;
                    $vtiger_order_item['row_total'] = $vtiger_order_item['price'] * $vtiger_order_item['qty_ordered'];
                    $vtiger_order_item['discount_amount'] = $vtiger_order_item['row_total'] * $discount_percent / 100;
                    $vtiger_order_item['base_row_total'] = $vtiger_order_item['row_total'] / $conversion_rate;
                    $vtiger_order_item['base_discount_amount'] = $vtiger_order_item['base_row_total'] * $discount_percent / 100;
                    $vtiger_order_item['row_total_incl_tax'] = $vtiger_order_item['row_total'] + $vtiger_order_item['tax_amount'];
                    $vtiger_order_item['base_row_total_incl_tax'] = $vtiger_order_item['row_total_incl_tax'] / $conversion_rate;
                    $subtotal += $vtiger_order_item['row_total'];

                    if (isset($products[$vtiger_order_item['product_id']])) {
                        $products[$vtiger_order_item['product_id']][1] = true;
                        $item = $products[$vtiger_order_item['product_id']][0];
                        $item->addData($vtiger_order_item)->save();
                        $parent_item = $item->getParentItem();
                        if (!is_null($parent_item) && $parent_item->getProductType() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
                            $vtiger_order_item['product_id'] = $parent_item->getProductId();
                            $vtiger_order_item['product_type'] = $parent_item->getProductType();
                            $parent_item->addData($vtiger_order_item)->save();
                        }
                    } else {
                        $parent_product = null;
                        $parent_item = null;
                        if ($product->getVisibility() == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE
                                && $product->getTypeId() == 'simple') {
                            $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
                            $parent_id = 0;

                            if (count($parentIds) > 0) {
                                foreach ($parentIds as $_parent_product_id) {
                                    $_parent_product = Mage::getModel('catalog/product')
                                                    ->setStoreId($order->getStoreId())->load($_parent_product_id);
                                    if (str_replace("!@#$%^" . $_parent_product->getSku(), "", "!@#$%^" . $product->getSku()) != "!@#$%^" . $product->getSku()) {
                                        $parent_id = $_parent_product_id;
                                        $parent_product = $_parent_product;
                                        break;
                                    } else if ($parent_id == 0) {
                                        $parent_id = $_parent_product_id;
                                        $parent_product = $_parent_product;
                                    }
                                }

                                $_attributes = $parent_product->getTypeInstance(true)
                                        ->getConfigurableAttributesAsArray($parent_product);
                                $attributes = array();
                                foreach ($_attributes as $_attribute) {
                                    $value_index = $product->getData($_attribute['attribute_code']);
                                    $values = $_attribute['values'];
                                    foreach ($values as $value) {
                                        if ($value['value_index'] == $value_index) {
                                            $value_index = $value['store_label'];
                                            break;
                                        }
                                    }
                                    $attributes[] = array(
                                        'label' => $_attribute['label'],
                                        'value' => $value_index
                                    );
                                }
                                $options = array(
                                    'attributes_info' => $attributes,
                                    'simple_name' => $parent_product->getName(),
                                    'simple_sku' => $product->getSku()
                                );

                                $parent_item = Mage::getModel('sales/order_item');
                                $vtiger_order_item['store_id'] = $order->getStoreId();
                                $vtiger_order_item['product_id'] = $parent_product->getId();
                                $vtiger_order_item['product_type'] = $parent_product->getTypeId();
                                $vtiger_order_item['product_options'] = serialize($options);

                                $parent_item->setData($vtiger_order_item);
                                $order->addItem($parent_item);
                                $parent_item->save();
                                $vtiger_order_item['product_id'] = $product->getId();
                                $vtiger_order_item['product_type'] = $product->getTypeId();
                                $vtiger_order_item['product_options'] = '';
                            }
                        }

                        $vtiger_order_item['original_price'] = floatval($product->getPrice()) * $conversion_rate;
                        $vtiger_order_item['base_original_price'] = floatval($product->getPrice());
                        $item = Mage::getModel('sales/order_item');
                        $item->setData($vtiger_order_item);
                        if (!is_null($parent_item)) {
                            $item->setParentItemId($parent_item->getId());
                        }
                        $order->addItem($item);
                        $item->save();
                        Mage::getModel('core/session')->setOrderCreatedNewItems(true);
                    }
                }

                $order->setTotalItemCount($total_item_count);
                foreach ($items as $item) {
                    $parent_item = $item->getParentItem();
                    if (!is_null($parent_item)) {
                        if ($products[$item->getProductId()][1]) {
                            $products[$parent_item->getProductId()][1] = true;
                        } else {
                            if ($products[$parent_item->getProductId()][1]) {
                                $products[$item->getProductId()][1] = true;
                            }
                        }
                    }
                }
                foreach ($products as $id => $value) {
                    if (!$value[1]) {
                        $value[0]->delete();
                    }
                }
            }
            $grand_total = $subtotal + $tax_amount + $shipping_amount - $discount_amount;
            $total_due = $grand_total - $order->getTotalPaid() - $order->getTotalRefunded();
            $order->setSubtotal($subtotal)->setBaseSubtotal($subtotal / $conversion_rate);
            $order->setTaxAmount($tax_amount)->setBaseTaxAmount($tax_amount / $conversion_rate);
            $order->setShippingAmount($shipping_amount)->setBaseShippingAmount($shipping_amount / $conversion_rate);
            $order->setDiscountAmount(-$discount_amount)->setBaseDiscountAmount(-$discount_amount / $conversion_rate);
            $order->setGrandTotal($grand_total)->setBaseGrandTotal($grand_total / $conversion_rate);
            $order->setTotalDue($total_due)->setBaseTotalDue($total_due / $conversion_rate);

            if ($status == 'pending' || $status == Mage_Sales_Model_Order::STATE_CANCELED
                    || $status == Mage_Sales_Model_Order::STATE_HOLDED
                    || $status == Mage_Sales_Model_Order::STATE_PROCESSING
                    || $status == Mage_Sales_Model_Order::STATE_CLOSED
                    || $status == Mage_Sales_Model_Order::STATE_COMPLETE) {
                if ($status == 'pending') {
                    if ($order->getStatus() != 'pending') {
                        $order->unhold();
                    }
                } else if ($status == Mage_Sales_Model_Order::STATE_HOLDED) {
                    if ($order->getStatus() != Mage_Sales_Model_Order::STATE_HOLDED) {
                        $order->hold();
                    }
                } else if ($order->getStatus() != Mage_Sales_Model_Order::STATE_CANCELED
                        && $order->getStatus() != Mage_Sales_Model_Order::STATE_CLOSED
                        && ($order->getStatus() != Mage_Sales_Model_Order::STATE_COMPLETE || ($order->getStatus() == Mage_Sales_Model_Order::STATE_COMPLETE && $status == Mage_Sales_Model_Order::STATE_CLOSED))) {
                    if ($status == Mage_Sales_Model_Order::STATE_CANCELED) {
                        $order->cancel();
                    } else if ($status == Mage_Sales_Model_Order::STATE_PROCESSING) {
                        $order->setStatus($status)->setState($status);
                    } else if ($order->getStatus() != Mage_Sales_Model_Order::STATE_HOLDED) {
                        foreach ($items as $item) {
                            if ($item instanceof Mage_Sales_Model_Order_Item) {
                                $qty_ordered = $item->getQtyOrdered();
                                $qty_invoiced = $item->getQtyInvoiced();

                                switch ($status) {
                                    case Mage_Sales_Model_Order::STATE_CANCELED:
                                        $item->setQtyCanceled($qty_ordered - $qty_invoiced);
                                        break;
                                    case Mage_Sales_Model_Order::STATE_CLOSED:
                                        $item->setQtyRefunded($qty_invoiced);
                                        $item->setQtyCanceled($qty_ordered - $qty_invoiced);
                                        break;
                                    case Mage_Sales_Model_Order::STATE_COMPLETE:
                                        $item->setQtyInvoiced($qty_ordered);
                                        $item->setQtyShipped($qty_ordered);
                                        break;
                                }
                            }
                        }

                        switch ($status) {
                            case Mage_Sales_Model_Order::STATE_CANCELED:
                                $order->setTotalCanceled($order->getTotalPaid())->setBaseTotalCanceled($order->getBaseTotalPaid());
                                break;
                            case Mage_Sales_Model_Order::STATE_CLOSED:
                                $order->setTotalRefunded($order->getGrandTotal() - $order->getTotalPaid());
                                $order->setBaseTotalRefunded($order->getTotalRefunded() * $conversion_rate);
                                break;
                            case Mage_Sales_Model_Order::STATE_COMPLETE:
                                $order->setTotalPaid($order->getGrandTotal())->setBaseTotalPaid($order->getBaseGrandTotal());
                                $order->setTotalInvoiced($order->getGrandTotal())->setBaseTotalInvoiced($order->getBaseGrandTotal());
                                $order->setTotalDue(0)->setBaseTotalDue(0);
                                break;
                        }
                        $order->setStatus($status)->setState(null);
                    } else if ($order->getStatus() == Mage_Sales_Model_Order::STATE_COMPLETE) {
                        $order->setTotalRefunded($order->getGrandTotal() - $order->getTotalPaid());
                        $order->setBaseTotalRefunded($order->getTotalRefunded() * $conversion_rate);
                        $order->setStatus($status)->setState(null);
                    }
                }
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::ORDER)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($order->getId())
                    ->setToId($order->getId())
                    ->setNumberSuccess(1)->setSuccessIds($order->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($order->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/order_subject_prefix') . $order->getIncrementId())->save();
            $order->setOrderCurrencyCode($order_currency_code)
                    ->setStoreToOrderRate($conversion_rate)
                    ->setBaseToOrderRate($conversion_rate)->save();

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Order %s have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $order->getId())), $order->getIncrementId()
                                )) . '<br/>';
            } else {
                return $order->getId();
            }
        } else {
            return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Order have been updated unsuccessfully. There is no order in your Magento store has Vtiger Id %s.', $vtigerId) . '<br/>';
        }
    }

    public function remoteInvoices($vtigerId, $showId = false, $data = null) {
        $return_id = false;
        if (is_null($data)) {
            $postData = array(
                'vtiger_id' => $vtigerId
            );
            $data = $this->post($postData);
            if ($data == '') {
                return 'error-' . Mage::helper('vtigersynchronization')->__("Error from Vtiger") . ": " . Mage::helper('vtigersynchronization')->__("Record undetermined") . '.<br/>';
            }
        } else {
            $return_id = true;
        }

        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $invoice = $data['crm4ecommerce'];

        $invoice_billing_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_INVOICE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::INVOICE_BILL);
        $invoiceBillData = array();
        foreach ($invoice_billing_mapping as $field) {
            $invoiceBillData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }

        $invoice_shipping_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_INVOICE, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::INVOICE_SHIP);
        $invoiceShipData = array();
        foreach ($invoice_shipping_mapping as $field) {
            $invoiceShipData[$field->getVtigerColumn()] = $field->getAttributeCode();
        }
        $invoice_bill_data = array();
        $invoice_ship_data = array();
        $states = Mage::getSingleton('sales/order_invoice')->getStates();
        $status = '';
        $invoice_id = 0;

        foreach ($invoice as $key => $value) {
            if ($key == 'remote_id') {
                $invoice_id = $value;
                continue;
            }
            switch ($key) {
                case 'invoicestatus':
                    foreach ($states as $status_key => $status_label) {
                        if ($status_label == $value) {
                            $status = $status_key;
                        }
                    }
                    break;
                default :
                    if (key_exists($key, $invoiceBillData) && $invoiceBillData[$key] != '') {
                        if ($invoiceBillData[$key] == 'country_id') {
                            $invoice_bill_data['country_id'] = $this->searchCountry($value);
                        } else {
                            $invoice_bill_data[$invoiceBillData[$key]] = $value;
                        }
                    }
                    if (key_exists($key, $invoiceShipData) && $invoiceShipData[$key] != '') {
                        if ($invoiceShipData[$key] == 'country_id') {
                            $invoice_ship_data['country_id'] = $this->searchCountry($value);
                        } else {
                            $invoice_ship_data[$invoiceShipData[$key]] = $value;
                        }
                    }
            }
        }

        $invoice = Mage::getModel('sales/order_invoice')->getCollection()
                ->addFieldToFilter('vtiger_id', array('eq' => $vtigerId))
                ->getFirstItem();
        if (!$invoice->getId() && (int) $invoice_id > 0) {
            $invoice = Mage::getModel('sales/order_invoice')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => $invoice_id))
                    ->getFirstItem();
        }

        if ($invoice->getId() > 0) {
            $invoice = Mage::getModel('sales/order_invoice')->load($invoice->getId());
            $order = $invoice->getOrder();

            $billads = $invoice->getBillingAddress();
            $billads->addData($invoice_bill_data)->save();
            $shipads = $invoice->getShippingAddress();
            if ($shipads) {
                $shipads->addData($invoice_ship_data)->save();
            }

            if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_CANCELED) {
                if ($order->getStatus() != Mage_Sales_Model_Order::STATE_CANCELED
                        && $order->getStatus() != Mage_Sales_Model_Order::STATE_CLOSED
                        && $order->getStatus() != Mage_Sales_Model_Order::STATE_COMPLETE) {
                    if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_PAID && $status == Mage_Sales_Model_Order_Invoice::STATE_PAID) {
                        $invoice->pay();
                    } else if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_CANCELED && $status == Mage_Sales_Model_Order_Invoice::STATE_CANCELED) {
                        $invoice->cancel();
                    } else if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_OPEN && $status == Mage_Sales_Model_Order_Invoice::STATE_OPEN) {
                        $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_OPEN);
                    }
                }
            }

            Mage::getModel('vtigersynchronization/log')
                    ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::INVOICE)
                    ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_VTIGER_REQUEST)
                    ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                    ->setFromId($invoice->getId())
                    ->setToId($invoice->getId())
                    ->setNumberSuccess(1)->setSuccessIds($invoice->getId())->setNumberFailure(0)
                    ->setFailureIds('')->setStatus(true)->addLogSuccess($invoice->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/invoice_subject_prefix') . $invoice->getIncrementId())->save();
            $invoice->save();
            $this->prepareOrderAfterRemoteInvoice($order);

            if (!$return_id) {
                return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Invoice %s have been updated successfully.', sprintf('<a target="_blank" style="color: white" href="%s">%s</a>', Mage::helper('adminhtml')->getUrl('adminhtml/sales_invoice/view', array('invoice_id' => $invoice->getId())), $invoice->getIncrementId()
                                )) . '<br/>';
            } else {
                return $invoice->getId();
            }
        } else {
            return ' - ' . ($showId ? '(Vtiger Id: ' . $vtigerId . ') ' : ' ') . Mage::helper('vtigersynchronization')->__('Invoice have been updated unsuccessfully. There is no invoice in your Magento store has Vtiger Id %s.', $vtigerId) . '<br/>';
        }
    }

    private function prepareOrderAfterRemoteInvoice(Mage_Sales_Model_Order $order) {
        $invoice_collection = $order->getInvoiceCollection();
        $paid = 0;
        $invoice_paid_item_collections = array();
        foreach ($invoice_collection as $invoice) {
            if ($invoice->getState() == Mage_Sales_Model_Order_Invoice::STATE_PAID) {
                $paid += $invoice->getGrandTotal();
                $invoice_paid_item_collections[] = $invoice->getItemsCollection();
            }
        }
        $order->setBaseTotalPaid(floatval($paid) / floatval($order->getBaseToOrderRate()));
        $order->setTotalPaid($paid);

        $order_item_collection = $order->getItemsCollection();
        foreach ($order_item_collection as $order_item) {
            $order_item_number_invoiced = 0;
            foreach ($invoice_paid_item_collections as $invoice_item_collection) {
                foreach ($invoice_item_collection as $invoice_item) {
                    if ($order_item->getId() == $invoice_item->getOrderItemId()) {
                        $order_item_number_invoiced += $invoice_item->getQty();
                    }
                }
            }
            $order_item->setQtyInvoiced($order_item_number_invoiced);
            $order_item->save();
        }
        $order->save();
    }

    private function getCustomerGenderName($gender_label) {
        $options = Mage::getResourceSingleton('customer/customer')->getAttribute('gender')->getSource()->getAllOptions();
        foreach ($options as $option) {
            if ($option['label'] == $gender_label) {
                return $option['value'];
            }
        }
    }

    public function remoteActivities($data = null) {
        $data = CRM4Ecommerce_VtigerSynchronization_Helper_XML2Array::createArray(base64_decode($data));
        $activities = $data['crm4ecommerce'];
        $comment_data = array();
        $comment_keys = array();
        $comment_mapping = null;
        $object = null;
        $_comment_history_collection = null;
        if ($activities['type'] == 'SalesOrder') {
            $order = Mage::getModel('sales/order')->load($activities['remote_id']);
            $comment_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                    ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_ORDER_COMMENT_VTIGER_ACTIVITY, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::ORDER_COMMENT);
            foreach ($comment_mapping as $field) {
                if ($field->getAttributeCode() == 'subject' ||
                        $field->getAttributeCode() == 'due_date' ||
                        $field->getAttributeCode() == 'time_end') {
                    continue;
                }
                $comment_keys[$field->getVtigerColumn()] = $field->getAttributeCode();
            }
            $object = Mage::getModel('sales/order')->load($activities['remote_id']);
            $comment_history_collection = $object->getStatusHistoryCollection();
            foreach ($comment_history_collection as $comment) {
                $_comment_history_collection[] = $comment;
            }
            for ($i = 0; $i < count($_comment_history_collection) - 1; $i++) {
                for ($j = $i + 1; $j < count($_comment_history_collection); $j++) {
                    if ($_comment_history_collection[$i]->getCreatedAt() > $_comment_history_collection[$j]->getCreatedAt()) {
                        $temp = $_comment_history_collection[$i];
                        $_comment_history_collection[$i] = $_comment_history_collection[$j];
                        $_comment_history_collection[$j] = $temp;
                    }
                }
            }

            $i = 0;
            $statuses = Mage::getSingleton('sales/order_config')->getStatuses();
            foreach ($activities['list'] as $_k => $_activity) {
                $_comment_data = array();
                foreach ($_activity as $key => $value) {
                    if (key_exists($key, $comment_keys) && $comment_keys[$key] != '') {
                        if ($comment_keys[$key] == 'status') {
                            foreach ($statuses as $v => $l) {
                                if ($l == $value) {
                                    $value = $v;
                                    break;
                                }
                            }
                        }
                        $_comment_data[$comment_keys[$key]] = $value;
                    }
                }
                if (!isset($_comment_data['status']) || $_comment_data['status'] == '') {
                    $_comment_data['status'] = $object->getStatus();
                }
                if (isset($_comment_history_collection[$i])) {
                    $created_at = $_comment_history_collection[$i]->getCreatedAt();
                    $_created_at = explode(' ', $created_at);
                    if ($_comment_data['date_start'] != '') {
                        $_created_at[0] = $_comment_data['date_start'];
                        unset($_comment_data['date_start']);
                    }
                    if ($_comment_data['time_start'] != '') {
                        $_created_at[1] = $_comment_data['time_start'];
                        unset($_comment_data['time_start']);
                    }

                    $_created_at = implode(' ', $_created_at);
                    if ($_created_at != $created_at) {
                        $_comment_data['created_at'] = $_created_at;
                    }
                    if (!$_comment_history_collection[$i]->getIsCustomerNotified() && isset($_comment_data['is_customer_notified']) && $_comment_data['is_customer_notified'] == '1'
                            && isset($_comment_data['comment']) && $_comment_data['comment'] != '') {
                        $order->sendOrderUpdateEmail(true, $_comment_data['comment']);
                    }
                    $_comment_history_collection[$i]->addData($_comment_data)->save();
                    $i++;
                } else {
                    $comment_data[] = $_comment_data;
                }
            }
            if ($i < count($_comment_history_collection)) {
                do {
                    $_comment_history_collection[$i]->delete();
                    $i++;
                } while ($i < count($_comment_history_collection));
            }

            foreach ($comment_data as $comment) {
                $created_at = '';
                if ($comment['date_start'] != '') {
                    $created_at = $comment['date_start'];
                    unset($comment['date_start']);
                }
                if ($comment['time_start'] != '') {
                    $created_at .= ' ' . $comment['time_start'];
                    unset($comment['time_start']);
                }

                $comment['created_at'] = $created_at;
                if (isset($comment['is_customer_notified']) && $comment['is_customer_notified'] == '1'
                        && isset($comment['comment']) && $comment['comment'] != '') {
                    $order->sendOrderUpdateEmail(true, $comment['comment']);
                }
                Mage::getModel('sales/order_status_history')->setOrder($object)->addData($comment)->save();
            }
            Mage::getModel('vtigersynchronization/synchronize_order')->save($order);
        } else {
            $invoice = Mage::getModel('sales/order_invoice')->load($activities['remote_id']);

            $comment_mapping = Mage::getModel('vtigersynchronization/mapping_field')
                    ->loadMappingFields(CRM4Ecommerce_VtigerSynchronization_Helper_Data::MAPPING_FIELDS_INVOICE_COMMENT_VTIGER_ACTIVITY, CRM4Ecommerce_VtigerSynchronization_Model_Array_MappingObjectType::INVOICE_COMMENT);
            foreach ($comment_mapping as $field) {
                if ($field->getAttributeCode() == 'subject' ||
                        $field->getAttributeCode() == 'due_date' ||
                        $field->getAttributeCode() == 'time_end') {
                    continue;
                }
                $comment_keys[$field->getVtigerColumn()] = $field->getAttributeCode();
            }
            $object = Mage::getModel('sales/order_invoice')->load($activities['remote_id']);
            $comment_history_collection = $object->getCommentsCollection(true);
            foreach ($comment_history_collection as $comment) {
                $_comment_history_collection[] = $comment;
            }
            for ($i = 0; $i < count($_comment_history_collection) - 1; $i++) {
                for ($j = $i + 1; $j < count($_comment_history_collection); $j++) {
                    if ($_comment_history_collection[$i]->getCreatedAt() > $_comment_history_collection[$j]->getCreatedAt()) {
                        $temp = $_comment_history_collection[$i];
                        $_comment_history_collection[$i] = $_comment_history_collection[$j];
                        $_comment_history_collection[$j] = $temp;
                    }
                }
            }
            $i = 0;
            foreach ($activities['list'] as $_k => $_activity) {
                $_comment_data = array();
                foreach ($_activity as $key => $value) {
                    if (key_exists($key, $comment_keys) && $comment_keys[$key] != '') {
                        if ($comment_keys[$key] == 'status') {
                            foreach ($statuses as $v => $l) {
                                if ($l == $value) {
                                    $value = $v;
                                    break;
                                }
                            }
                        }
                        $_comment_data[$comment_keys[$key]] = $value;
                    }
                }
                if (isset($_comment_history_collection[$i])) {
                    $created_at = $_comment_history_collection[$i]->getCreatedAt();
                    $_created_at = explode(' ', $created_at);
                    if ($_comment_data['date_start'] != '') {
                        $_created_at[0] = $_comment_data['date_start'];
                        unset($_comment_data['date_start']);
                    }
                    if ($_comment_data['time_start'] != '') {
                        $_created_at[1] = $_comment_data['time_start'];
                        unset($_comment_data['time_start']);
                    }

                    $_created_at = implode(' ', $_created_at);
                    if ($_created_at != $created_at) {
                        $_comment_data['created_at'] = $_created_at;
                    }
                    if (!$_comment_history_collection[$i]->getIsCustomerNotified() && isset($_comment_data['is_customer_notified']) && $_comment_data['is_customer_notified'] == '1'
                            && isset($_comment_data['comment']) && $_comment_data['comment'] != '') {
                        $invoice->sendUpdateEmail(true, $_comment_data['comment']);
                    }
                    $_comment_history_collection[$i]->addData($_comment_data)->save();
                    $i++;
                } else {
                    $comment_data[] = $_comment_data;
                }
            }
            if ($i < count($_comment_history_collection)) {
                do {
                    $_comment_history_collection[$i]->delete();
                    $i++;
                } while ($i < count($_comment_history_collection));
            }

            foreach ($comment_data as $comment) {
                $created_at = '';
                if ($comment['date_start'] != '') {
                    $created_at = $comment['date_start'];
                    unset($comment['date_start']);
                }
                if ($comment['time_start'] != '') {
                    $created_at .= ' ' . $comment['time_start'];
                    unset($comment['time_start']);
                }

                $comment['created_at'] = $created_at;
                if (isset($comment['is_customer_notified']) && $comment['is_customer_notified'] == '1'
                        && isset($comment['comment']) && $comment['comment'] != '') {
                    $invoice->sendUpdateEmail(true, $comment['comment']);
                }
                Mage::getModel('sales/order_invoice_comment')->setInvoice($object)->addData($comment)->save();
            }
            Mage::getModel('vtigersynchronization/synchronize_invoice')->save($invoice);
        }
    }

}